0

From this regex,

text.replace(/^\s+|\s+$/g,"").replace(/  +/g,' ')

how do I remove the regex just for trailing white space?

I am new to regex and did some research but I'm not able to understand the pattern.

Boaz
  • 19,892
  • 8
  • 62
  • 70
user2019989
  • 19
  • 1
  • 2

1 Answers1

3

/^\s+|\s+$/g means

^    // match the beginning of the string
\s+  // match one or more whitespace characters
|    // OR if the previous expression does not match (i.e. alternation)
\s+  // match one or more whitespace characters
$    // match the end of the string

The g modifier indicates to repeat the matching until no match is found anymore.

So if you want to remove the part the matches whitespace characters at the end of the string, remove the |\s+$ part (and the g flag since ^\s+ can only match at one position anyway - at the beginning of the string).


Useful resources to learn regular expressions:

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Great way to answer the question for the lazy OP... You give him all the info he needs to answer his question, but don't give him that verbatim "_copy/paste_" solution that he's looking for! – jahroy Jan 29 '13 at 00:33
  • 1
    @jahroy - not looking for copy paste solution - trying to understand how regex works - its always been a hardest task for me, dont bother if you do not want to answer - why do you want to interefer here in the first pplace. some people just want to make such comments I think. – user2019989 Jan 29 '13 at 00:38
  • @ Felix Kling - thanks man i appreciate your help. much clear now. – user2019989 Jan 29 '13 at 00:38