Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of (/^\s+|\s+$/gm) in JavaScript?

I came across this JavaScript function:

function myTrim(x) {
  return x.replace(/^\s+|\s+$/gm,'');
}

I know that this function(mytrim()) replaces some characters in the string(x), but what does /^\s+|\s+$/gm do in the replace method?

Where can I learn more about these things?

Note- This function returns the string with removed spaces at both sides.

like image 964
aryaman Avatar asked Mar 10 '18 13:03

aryaman


2 Answers

It is a regular expression search that matches two alternative patterns:

/^\s+|\s+$/gm

/ Regex separator

First Alternative ^\s+

  • ^ asserts position at start of a line
  • \s+ matches any whitespace character (equal to [\r\n\t\f\v ])
  • + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

Second Alternative \s+$

  • \s+ matches any whitespace character (equal to [\r\n\t\f\v ])
  • + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
  • $ asserts position at the end of a line

Global pattern flags

  • g modifier: global. All matches (don't return after first match)
  • m modifier: multi line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)

You can read more details on regex101.com.

Function explanation

The function call return x.replace(/^\s+|\s+$/gm,''); searches for any spaces from the beginning of the string and from the end of string. If found then it is replaced by empty string ''. Simply said it does the trim whitespace characters:

  • \n carriage return (ASCII 13)
  • \r line-feed (newline) character (ASCII 10)
  • \t tab character (ASCII 9)
  • \f form-feed character (ASCII 12)
  • \v any vertical whitespace character
like image 177
ino Avatar answered Sep 29 '22 12:09

ino


This syntax is called a regular expression (often shortened to RegEx); there are multiple places you can learn this, but you can try this one.

There are also multiple websites to test such regular expressions such as regex101.com. Note that regular expressions are not a universal standard; there are variants depending on the programming language and platform (for example, grep, extended grep, Perl, Java, etc.).

like image 30
Simon Berthiaume Avatar answered Sep 29 '22 14:09

Simon Berthiaume