Skip to main content

JavaScript: Trimming Whitespaces (Regular Expression)

For Example

We want to tidy up the horizontal indentation of this typed words —

to be —

In that case, we need to:

  1. Find every more-than-1-whitespace pattern from the string.

    For that, we can employ regular expression (RegExp) method.

  2. Replace each with one space character.

    Replacing string can be achieved using replace() method.


Function Snippet

Very short.

Or, using arrow syntax


What Happened There?

The trimSpace function accepts an argument, that is the string we want to trim.

Then it will output the trimmed string.


The Trimming Process

I use /\s+/g to find matching pattern which consists of multiple whitespaces.

Let's have a look at every bit of that RegExp pattern and syntax.

  1. The opening and closing slashes / / are the identifier for RegExp object.

    We can also use new RegExp("string pattern", "flags") in JavaScript.

    For instance:

    More on MDN about new RegExp()

  2. The \s is the RegExp metacharacter for whitespace.

    The whitespace includes –

    • space,
    • tab (\t),
    • form feed (\f),
    • carriage return (\r),
    • and new line (\n).
  3. The + is the quantifier to match all pattern which consists of the previous character that occurs one or more times.

    In this example, the character is the whitespace (\s).

    We can also use {2,} quantifier if we want to be more specific. So the literal notation would be —

    It means look for two or more times repeated whitespaces.

  4. The g is the RegExp modifier (or flag) for global search of the text.

Then, each of the findings will be set to just one horizontal space using replace method. That " " bit, from —


Usage

We can:

  1. Just use the method, not declaring the process as a function.
  2. Use the constructed function. So that that particular process can be conveniently reused.

You can open your browser (Chrome, preferably) developer console, and copy-paste this, then hit enter or return. You'll see the result.

Not using the function, just direct method

Using a function definition


That'd be all. Thanks for visiting. 👋

Monkey Raptor uses cookies for analytics, advertisements, and functionality. Privacy Policy