For Example
We want to tidy up the horizontal indentation of this typed words —
to be —
In that case, we need to:
-
Find every more-than-1-whitespace pattern from the string.
For that, we can employ regular expression (
RegExp) method. -
Replace each with one space character.
Replacing string can be achieved using
replace()method.
Function Snippet
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.
-
The opening and closing slashes
/ /are the identifier forRegExpobject.We can also use
new RegExp("string pattern", "flags")in JavaScript.For instance:
More on MDN about
new RegExp() -
The
\sis theRegExpmetacharacter for whitespace.The whitespace includes –
- space,
- tab (
\t), - form feed (
\f), - carriage return (
\r), - and new line (
\n).
-
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.
-
The
gis theRegExpmodifier (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:
- Just use the method, not declaring the process as a function.
- 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. 👋