For example
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.
Let's construct a JavaScript function for that
Very short.
What happened there?
The
trim_space
function accepts a passed string argument.Then it will output the trimmed one.
The trimming process
I use
/\s+/g
to find matching pattern which consists of multiple whitespaces.
- The opening and closing slashes
/ /
are the identifier forRegExp
object.We can also use new RegExp("the_pattern", "flag/modifier") in JavaScript.
- The
\s
is theRegExp
metacharacter for whitespace.
The whitespace includes space character, tab character (\t
), form feed (\f
), carriage return (\r
), and new line (\n
). - The
+
is the quantifier to match all pattern which consists of the previous element.
In this example, the element is the whitespace (\s
). - The
g
is theRegExp
modifier (or flag) for global search of the text.
Usage
We can:
- 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
RegExp
and manipulating string (in any programming language).
No comments:
Post a Comment
Tell me what you think...