We wanna fix the horizontal indentation of this typed words:
To be just:
In that case, we need to:
- Find every more-than-1-whitespace pattern in the text.
That can be done using regular expression method.
- Replace each with just one space character.
Replacing string can be achieved using replace() method.
What happened there?
trim_spacefunction accepts a passed string argument.
Then it will output the trimmed one.
The trimming process
/\s+/gto find matching pattern which consists of multiple whitespaces.
- The opening and closing slashes
/ /are the identifier for
RegExpmetacharacter for whitespace.
The whitespace includes space character, tab character (
\t), form feed (
\f), carriage return (
\r), and new line (
+is the quantifier to match all pattern which consists of the previous element.
In this example, the element is the whitespace (
RegExpmodifier (or flag) for global search of the text.
- Just use the method, not declaring the process in a function.
- Use the constructed function. So that that particular process can be used over and over again for different thingies.
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 the function:
This method is useful to "neatify" the submitted input form text value.
Right that's it.
You can find deeper theories and focused topics on the internet about finding complex patterns using
RegExpand manipulating string (in any programming language).