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.
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 lineGlobal 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 characterThis 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.).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With