Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this JavaScript RegExp work?

I am lost about how this works:

x=x.replace(/^\s+|\s+$/g,"");

What is the pipe( | ) for ?

like image 447
Caffeinated Avatar asked Mar 19 '26 21:03

Caffeinated


2 Answers

The pipe means "or".

So your regex matches

^    # the start of the string
/s+  # followed by whitespace (one or more characters)
|    # or
/s+  # whitespace
$    # followed by the end of the string

The /g (global) modifier applies the regex to all matches in the string, not just the first one.

like image 85
Tim Pietzcker Avatar answered Mar 21 '26 09:03

Tim Pietzcker


It means or. The part to the left matches any leading spaces (^), the part to the right matches any trailing space ($). The g modifier allows this matching to be applied more than once, which is useful if you're expecting both trailing and leading space.

Basically this regex trims whitespace.

An alternative way to write this regex is, using the new RegExp construct:

x = x.replace(new RegExp("^\s+|\s+$", "g"), "");

If find this notation more readable because you don't need your delimiters (/) and your modifier is separated.

like image 36
Halcyon Avatar answered Mar 21 '26 09:03

Halcyon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!