Space can be present at any position in a string and, a single solution will not work in every situation.
- Remove all extra spacing between words.
- Trim the extra space from the beginning or end of a string.
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() 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!