Skip to main content

JavaScript: Trimming Leading-Trailing Whitespaces

Before we start, there's a post about replacing more than one white spaces to only one horizontal space.


Modern Browser

To trim leading / trailing whitespaces on modern browser, we can simply use trim() method:

Example:


Regular Expression

Details:

  • The ^ is to match the starting string.
  • The $ is to match the back of the string.
  • The \s is to match all white space criteria (horizontal space, tab, carriage, and so on).
  • The + is to match one or more repetition.
  • The | is the OR operator.
  • The g is to match globally (the entire string).

So this regular expression pattern /^\s+|\s+$/g can be translated to words as:

Find all (1 or more repetition of) whitespace which is located in front OR at the back of the entire string.

To be more complete:

Details:

  • The [..] brackets are to group characters. Find all the character combinations inside the brackets.
  • The \uFEFF is a boundary character: "zero width no-break space" or "byte order mark".
  • The \xA0 is a &nbsp character: "no-break space".

Replacing Found Pattern

We can use the RegExp pattern above for the replace() method:

SYNTAX

USAGE

Or, like so:

Combining it with more-than-1-white-space trimmer:

The "more-than-1-white-space" finder pattern can be —

  1. /\s+/g
  2. or, to be more specific ➡️ /\s{2,}/g

The second pattern (/\s{2,}/g) will look for 2 or more repetitions of whitespace globally.

The first one (/\s+/g) will look for 1 or more repetitions of whitespace globally.

The advantage of the first one is that we can strip new line / tab / other than horizontal space, and then replace it with just one horizontal space. But of course, it depends on your goal. It can be a disadvantage.

Let's use the first one as an example, /\s+/g pattern:

Or:

As you can see, the replace() can be conveniently chained.

replace() method can also have a callback function to further manipulate the string:

More information on MDN about replace and replaceAll.

replaceAll was introduced in ES2021 (ECMAScript 2021) in June 2021. It's a bit different than replace. In this post, I'm using replace.

Right, then. Let's continue.

Or, using trim():


Construct as a Function

As such:

Using the function trimAll:

The function trimAll only accepts String type of argument (the input). Other than that, you'll see error on your browser console.

You may need to add a validator for the input type. For instance:

Use that check in that function — but we flip the operator:


👋

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