Use a replace() and trim() method to Remove whitespace of string in JavaScript(). The trim() method do not support in browsers, you can remove whitespaces from both sides of a string or between words using replace() method with a regular expression:
Methods in JS to remove string whitespace
- replace() – Used with regular expression.
- trim() – Remove whitespace from string.
- trimLeft() – Remove the white spaces from the start of the given string.
- trimRight() – Remove the white spaces from the end of the given string.
Examples of JS Remove whitespace
1. replace()
For space-character removal use.
"hello world".replace(/\s/g, "");
Use the regex and replace() method to remove all space in the string. Below an example with an alert() box.
<!DOCTYPE html>
<html>
<body>
<p id="txt"> </p>
<script type="text/javascript">
var str = " Hello World! ";
alert(str);
</script>
</body>
</html>
Output:
Other solution for same:
str = str.replace(/\s+/g, '');
The Regex
\s
is the regex for “whitespace”, and g
is the “global” flag, meaning match ALL \s
(whitespaces).
2. trim()
Syntax –
str.trim()
The trim() method will remove whitespace from the beginning and end of the string in JavaScript. It does not change the original string.
<!DOCTYPE html>
<html>
<script type="text/javascript">
var str = " Hello World! ";
alert(str.trim());
</script>
<body>
</body>
</html>
3. str.trimLeft()
If you want a remove only remove the white spaces from the start of the strings.
<script type="text/javascript">
var str = " Hello World! ";
alert(str.trimLeft());
</script>
4. str.trimRight()
The function is used to remove the white spaces from the end of the string.
<script type="text/javascript">
var str = " Hello World! ";
alert(str.trimRight());
</script>
Q: How to javascript remove spaces between words?
Answer: To Removing All Spaces From a String use regular expressions. Here is code for it:-
var str = "E Y E H U N T S"
str = str.replace(/\s/g,'');
// Outputs 'EYEHUNTS'
Q: How to javascript remove extra spaces?
Answer: Let’s see the below example.
Input:
this contains spaces
Output:
this contains spaces
Remember that replace
replaces the found text with the second argument. So:
newString = string.replace(/\s+/g,''); // "thiscontainsspaces"
Finds any number of sequential spaces and removes them. Try replacing them with a single space instead!
newString = string.replace(/\s+/g,' ').trim();
Source: https://stackoverflow.com/questions/16974664/remove-extra-spaces-in-string-javascript
Do comment if you know any other way to do it or any doubts.
Note: The All JS Examples codes are tested on Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version