How to Delete Spaces from a String in JavaScript?

Estimated read time 2 min read

You can delete spaces from a string in JavaScript using the replace() method with a regular expression. Here’s an example:

const myString = "   This is a string with spaces.   ";
const trimmedString = myString.replace(/\s+/g, "");
console.log(trimmedString); // "Thisisastringwithspaces."

In this example, we first define a string myString with spaces at the beginning and end. We then call the replace() method on the string, passing in a regular expression that matches one or more whitespace characters (\s+) and the global flag (g) to replace all occurrences of whitespace. The second argument to replace() is an empty string, which replaces each match with nothing.

The resulting string, trimmedString, contains the original string with all spaces removed.

Note that the replace() method returns a new string and does not modify the original string. If you want to modify the original string in place, you can assign the result back to the original variable:

let myString = "   This is a string with spaces.   ";
myString = myString.replace(/\s+/g, "");
console.log(myString); // "Thisisastringwithspaces."

In this example, we first define a string myString with spaces at the beginning and end. We then call the replace() method on the string and assign the result back to myString. The original string is now replaced with the trimmed string.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply