remove space from string javascript

Remove Space From String in JavaScript

If you want to remove spaces from a string using JavaScript, there are multiple ways to do it. Here are some of the ways:

Using String.replace() method

The easiest way to remove spaces from a string is by using the replace() method of the string object.


const str = "hello world";
const newStr = str.replace(/ /g, "");
console.log(newStr);
// Output: helloworld

In the above example, we are using the replace() method with a regular expression to match all the spaces in the string and replace them with an empty string.

Using JavaScript split() and join() methods

You can also remove spaces from a string using the split() and join() methods of the string object.


const str = "hello world";
const newStr = str.split(" ").join("");
console.log(newStr);
// Output: helloworld

In the above example, we first use the split() method to split the string into an array of substrings using the space as a separator, and then we join the substrings back together using an empty string as a separator.

Using Regular Expression

You can use regular expression to remove spaces from a string. Here's an example:


const str = "hello world";
const newStr = str.replace(/\s/g, '');
console.log(newStr);
// Output: helloworld

The regular expression /\s/g matches all whitespace characters in the string and the replace() method replaces them with an empty string.

Conclusion

These are some of the ways to remove spaces from a string in JavaScript. You can use any of the above methods depending on your requirements.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe