Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
156
rated 0 times [  159] [ 3]  / answers: 1 / hits: 35846  / 6 Years ago, sat, march 10, 2018, 12:00:00

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.


More From » regex

 Answers
21

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 [rntfv ])

  • + 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 [rntfv ])

  • + 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


[#54974] Wednesday, March 7, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
micah

Total Points: 295
Total Questions: 104
Total Answers: 92

Location: Namibia
Member since Mon, Feb 21, 2022
2 Years ago
;