javascript

Remove space from string in javascript

Playing with strings in Javascript is a bit tricky. In this article, I am going to describe how to remove space from any string in Javascript.

Even though Javascript provides many inbuilt string functions, we must always aim for using the optimal one to solve any challenge.

Because JavaScript uses the main UI thread and any redundancy can cause a lag in the UI.

Space can be present at any position in a string and, a single solution will not work in every situation.

In this article, we will discuss the below topics.

  1. Remove all extra spacing between words.
  2. Trim the extra space from the beginning or end of a string.

Remove all extra space from string in javascript.

Let’s take an example string like below.

var sampleString = "The    quick   brown fox      jumped  over";

You can see that the spaces between the words are uneven. So, the end goal is to remove all extra blank spaces from in between.

To get that result, we are going to use the replace() function. The replace() method takes two parameters. The first parameter denotes an element which we want to replace all over the string. 

We can pass either an actual character or a string or a regex in the first parameter. In our example, we are using a regex (/\s+/g), which denotes all consecutive blank spaces.

The second parameter is the element which will replace all the occurrences of the first parameter. See the below code.

var sampleString = "The    quick   brown fox      jumped  over";
sampleString = sampleString .replace(/\s+/g, " ");
console.log(sampleString);
//The quick brown fox jumped over"; 

In the second line, take a look at the replace() function. The first parameter /\s+/g which refers to the consecutive set of white space characters.

The second parameter is the single space which will replace all the continuous blank spaces.

Trim the extra space from the beginning or end of a string.

Javascript has an inbuild trim() function for this purpose. The trim function takes one parameter, the string itself and, it returns a trimmed string.

The syntax looks like below:

var content = "      The Quick!       ";
console.log(content.trim());
//The Quick! 

Leave a Comment

thirty four + = thirty nine