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

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

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.).