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
\sis 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
gis to match globally (the entire string).
So this regular expression pattern /^\s+|\s+$/g can be translated to words as:
To be more complete:
Details:
- The
[..]brackets are to group characters. Find all the character combinations inside the brackets. - The
\uFEFFis a boundary character: "zero width no-break space" or "byte order mark". - The
\xA0is a 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 —
/\s+/g- 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:
👋