JavaScript Remove whitespace of String | Beginning & End, Between

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.

Use the regex and replace() method to remove all space in the string. Below an example with an alert() box.


String with space
replace() method to remove all space

Other solution for same:

The Regex

\s is the regex for “whitespace”, and g is the “global” flag, meaning match ALL \s (whitespaces).

2. trim()

Syntax –

The trim() method will remove whitespace from the beginning and end of the string in JavaScript. It does not change the original string.

3. str.trimLeft()

If you want a remove only remove the white spaces from the start of the strings.

4. str.trimRight()

The function is used to remove the white spaces from the end of the string.

Q: How to javascript remove spaces between words?

Answer: To Removing All Spaces From a String use regular expressions. Here is code for it:-

Q: How to javascript remove extra spaces?

Answer: Let’s see the below example.



Remember that replace replaces the found text with the second argument. So:

Finds any number of sequential spaces and removes them. Try replacing them with a single space instead!


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

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.