How to Delete Whitespace in JavaScript?

Estimated read time 2 min read

In JavaScript, you can remove whitespace from a string using a variety of methods. Here are a few examples:

  1. Using the replace() method with a regular expression:
const str = "  Hello, world!  ";
const trimmed = str.replace(/^\s+|\s+$/g, ''); // removes whitespace from both ends of the string

console.log(trimmed); // Output: "Hello, world!"

In this example, the replace() method is called on the original string str with a regular expression that matches whitespace characters at the beginning (^\s+) and end (\s+$) of the string. The g flag ensures that all matches are replaced, not just the first one.

  1. Using the trim() method:
const str = "  Hello, world!  ";
const trimmed = str.trim(); // removes whitespace from both ends of the string

console.log(trimmed); // Output: "Hello, world!"

In this example, the trim() method is called on the original string str. This method removes whitespace characters from both ends of the string.

  1. Using the replace() method with a whitespace character:
const str = "  Hello, world!  ";
const trimmed = str.replace(/\s/g, ''); // removes all whitespace from the string

console.log(trimmed); // Output: "Hello,world!"

In this example, the replace() method is called with a regular expression that matches any whitespace character (\s) in the string. The g flag ensures that all matches are replaced, not just the first one.

All of these methods will return a new string with the whitespace removed. Be aware that replace() and trim() return a new string, and do not modify the original string.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply