Skip to content
the poor coder

remove space from string javascript

Poor Man
Published
Reading time
1 min read
On this page

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.

Text

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.

Text

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:

Text

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC