2

I am lost about how this works:

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

What is the pipe( | ) for ?

2
  • @PeeHaa - Ah, yes( I need coffee!). what of the /g part? Commented Mar 26, 2012 at 19:59
  • I see you're reading the same book that I am :) Commented Sep 7, 2013 at 11:00

6 Answers 6

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The modifier is just g, the / is part of the delimiter which indicates the end of the regular expression.
3

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.

Comments

2

It's an alternation construct.

The regex says "either the beginning-of-string followed by one or more whitespace characters, OR, one or more whitespace characters followed by end-of-string".

I think that is the intent, anyway. I'm not sure now that I read JaredPar's answer.

If I were writing this I would use parens to make it explicit.

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

1 Comment

This is incorrect. ^ and $ match the end of the string, not the end of the line, unless the /m modifier is used, which it isn't.
1

That "pipe" in regex stands for an "OR" so your regex will either match the pattern before the "pipe" either the pattern after the "pipe"

Comments

1

The pipe character "|" represents "or".

Comments

1

Pipe is represent OR
/g represents Global
\s represents Space

1 Comment

\s means "whitespace character" (which includes standard space, tab, carriage return, line feed, and more obscure ones as well)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.