Monkey Raptor

Saturday, January 31, 2015

JavaScript: Trimming Whitespaces (Regular Expression)

This is a quick snippet you can use (and expand for other pattern).


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.
  1. The opening and closing slashes / / are the identifier for RegExp object.
    We can also use new RegExp("the_pattern", "flag/modifier") in JavaScript.
  2. The \s is the RegExp metacharacter for whitespace.
    The whitespace includes space character, tab character (\t), form feed (\f), carriage return (\r), and new line (\n).
  3. The + is the quantifier to match all pattern which consists of the previous element.
    In this example, the element is the whitespace (\s).
  4. The g is the RegExp modifier (or flag) for global search of the text.
Then, each of the findings will be set to just one horizontal space.


Usage
We can:
  1. Just use the method, not declaring the process in a function.
  2. 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).
JavaScript: Trimming Whitespaces (Regular Expression)
https://monkeyraptor.johanpaul.net/2015/01/javascript-trimming-whitespaces-regular.html?m=0

No comments

Post a Comment

Tell me what you think...