In this tutorial, we’re going to look at different to replace and remove spaces from string in JavaScript.
We’ll be using a combination of pre-defined string methods in JavaScript to start with, and then finish the tutorial with an example of how we’ll solve the issue manually, without any pre-defined methods.
Let’s get right into it, shall we?
Remove all spaces using ReplaceAll function
To start with, let’s look at a very simple example. Let’s say we have a string with 1 space between each character, and t avoid confusion, let’s say the string just has one word to it.
So now, all we need to do is, remove all the single spaces, and replace them with nothing. We can’t replace ‘something’ with ‘nothing’ in programming though. We need a condition. That condition would be the ‘empty string’ in our case, which is equivalent to saying replace the space with nothing.
We’ll be using the replaceAll method in JavaScript to achieve this. It’s a very simple method that can be used to solve simple problems like this. You know example what you want replaced (a single space) and what you want it replaced with (empty space).
So, the first argument of the replaceAll function call should be a single space, and the second argument should be an empty space.
Let’s look at how to do the same in code:
let str = "H e l l o !"; str = str.replaceAll(' ', ''); console.log(str);
That’s it! Now, run the above code, and you’ll get:
There you go! All the extra single spaces were removed.
This code would work if your string had more than one space between the characters too. Why don’t you try it out and see for yourself?
Replace all spaces using ReplaceAll function
If you’d like to replace the spaces with something else, like a dot or a dash, for example, all you have to do is give the same as the second argument of the replaceAll function call.
In the below example, we’ve given a dot as the replacement.
let str = "H e l l o !"; str = str.replaceAll(' ', '.'); console.log(str);
You’ll get the following output:
It’s as simple as that!
Remove all spaces using Replace function
Now, let’s look at things a little bit more complicated. With the ‘replace’ method, you can use regular expressions as your first argument, and that opens up a whole new world for you.
With regular expressions, you can given specific conditions.
For example, you can say
1. Remove the first space, and only that
2. Remove the last space, and only that
3. Remove all the single spaces
4. Remove all the double spaces, and only those
And so on.
The sky’s the limit, really.
Regular expressions is a vast subject, so I won’t be covering it all in this tutorial. I will, though, cover enough to solve the problems we’re tackling on here.
To start with, let’s look at how to solve the previous problem with the ‘replace’ method. Use the replace method, and the condition should be replace a single space with an empty space, just like we did before.
let str = "H e l l o !"; str = str.replace(' ', ''); console.log(str);
Now, if you run the above line of code, you’ll get:
Something’s not right here. The space between ‘H’ and ‘e’ is gone, but the remaining spaces are still there. Why’s that?
Well, that’s because the ‘replace’ method as such, just removes the first instance of the given condition (single space, in this instance) and nothing else.
If you’d like to remove all the instances of the given condition, you need regular expressions. To use regular expressions, you just need to enclose the character you need replaced within 2 front slashes, like this ‘/ /’.
But that won’t be enough either. To truly remove every instance of the string, you need to use the global flag. Place a ‘g’ right after the last front slash, and your browser will understand that you want to remove every single instance of that character from the given string.
The above explanation, in code format, is as follows:
str = str.replace(/ /g, '');
If you run the above line of code, you’ll get the string without any spaces, just like before.
Replace all spaces using Replace function
You can use the same regular expression with a global flag to replace the spaces instead of removing it, just like we did before.
str = str.replace(/ /g, '.');
Remove all spaces, tabs and new lines from a string
So far, we’ve been looking at removing spaces, but what if you’re dealing with extra tabs or new lines? If you’d like to remove those, you need the \s flag. This flag includes spaces as well, so if you want to be inclusive, you’re better off using the \s flag from the get-go.
Let’s look at an example now. Let’s say you have string with a new line, and a tab.
let str = 'Hello !\nHow are you?'; console.log(str);
If you look at the output of this string, you’ll get the following:
Look at that! You can clearly see the tab and the new line. Now, let’s go ahead and replace those.
str = str.replace(/\s/g, ''); console.log(str);
Look at the output now.
Perfect!
Trim excess space in JavaScript
Sometimes, your computer generates extra spaces at the start or the end of a string, or both. Those can be trimmed without using regular expressions. Let’s see how to do that.
let str = " Hello there! "; str = str.trim(); console.log(str);
In the above example, we have extra spaces both at the start and the end of the string, and I’ve used the trim() method in JavaScript to remove them.
Look at the output now:
The string has been trimmed just the way we want it.
But this doesn’t work for spaces in between, like the following:
let str = " Hello there! ";
For these, you need to remove the extra spaces after you’ve trimmed the string.
let str = " Hello there! "; str = str.trim(); console.log(str); str = str.replace(/\s{2}/,''); console.log(str);
In the above example, we trimmed the string to remove the leading and trailing spaces, and then, used the replace method to remove exactly 2 spaces from the string (the {2} condition can be used to remove exactly how many continuous instances of the character you need). This leaves us with exactly 1 space between the words.
Let’s look at the output now, and:
Great! Works perfectly.
Remove only extra spaces from string with JavaScript
But things don’t always work out the way you want them to. Sometimes, you might end up with a problem where things aren’t so cut and dry.
Let’s say you have a string like the following:
let str = "H e l l o W o r l d !";
You have a string with a single space between each character, and 2 spaces between the words. Here, we want to remove the spaces between the character and 1 space between the word. How do we do that?
Well, we have to get a little creative here. Why don’t we split the string at 2 spaces, to start with? We’ll end up with 2 words, split over an array, like this:
str = str.split(' '); console.log(str);
Now str has become an array, and will look like this:
Now, we can manually traverse every character in each word (which is 2 in this case), and replace the single spaces with an empty string, as usual. Why don’t we trim the string as well, just to be sure?
for(let i=0; i<str.length; i++) { str[i] = str[i].replace(/ /g,'').trim(); } console.log(str);
Look at the array now, and you’ll get the following:
Now all we need to do is join the 2 words with a single space in between, like this:
str = str.join(' '); console.log(str);
Look at the output now, and you’ll have:
This is exactly what we needed.
So, now that you know how to use the various JavaScript string methods to remove or replace spaces, you can get creative while solving the problems you end up with.
If there are 3 spaces separating, still would work (because of trim()).
let str = "H e l l o W o r l d !";
Why don’t you try it out?
Remove leading spaces in string JavaScript
If you’d like to remove just the leading spaces in a string and leave the trailing spaces alone, you can use trimStart(), as shown below:
let str = " Hello there! "; str = str.trimStart(); console.log(str);
The output for the above would be:
Look at that. The trailing spaces are still there.
Remove trailing spaces in string JavaScript
Similarly, if you’d like to remove just the trailing spaces, use trimEnd().
str = str.trimEnd();
Manually remove the spaces using JavaScript
It’s quite simple to manually removes spaces. All you need to do is just pluck the characters that are not spaces from the string, and string them together inside a new variable. You’re good to go!
let str = "H e l l o !"; let newStr = ''; for(let i = 0; i < str.length; i++) { let j = 0; if(str[i] !== ' ') { newStr = newStr + str[i]; j++; } } console.log(newStr);
In the above example, we’ve created a new string newStr, and we’ve assigned it an empty string to start with.
Then, we go through the string, and if a particular character in an iteration is not a space, we concatenate newStr with that character.
This creates a new string with no spaces.
You can modify this method to come up with solutions for other problems of this type as well.
Well, there you go! We’ve looked at multiple ways of removing character from a string in JavaScript! There’s still a lot that can be done in this space, but now you know the basics needed to create your own solutions.
All the best!