0

I'd like to clarify two doubts about javascript Regexs.

  1. Is it possible to nest a second OR expression inside a primary one, as below (v|b|c):

    /(value1|value2|value3|(v|b|c)alue4)/
    
  2. Is it possible to break lines into the same expression, as below (in order to be more readable):

    /(value1|
      value2|
      value3|
      (v|b|c)alue4)
    /
    

Thanks so much

2
  • 1
    For part1, have you tried it out? /(value1|value2|value3|(v|b|c)alue4)/.test("balue4") Commented Feb 24, 2015 at 17:09
  • 1) yes you can 2) no you cannot Commented Feb 24, 2015 at 17:09

2 Answers 2

4

Why don't you try it yourself?

Example 1

/(value1|value2|value3|(v|b|c)alue4)/.test("calue4")
-> true

Example 2

/(value1|
  value2|
  value3|
  (v|b|c)alue4)
/.test("calue4")
->  Uncaught SyntaxError: Invalid regular expression: missing /

If you really want to use that multi-line style, you can always use string concatenation and the RegExp object:

new RegExp("(value1|" +
           "value2|" +
           "value3|" +
           "(v|b|c)alue4)").test("calue4")
-> true
Sign up to request clarification or add additional context in comments.

Comments

3

To expand on James answer; you can also escape newlines in a string instead of concatenating several strings.

new RegExp("(value1|\
value2|\
value3|\
(v|b|c)alue4)").test("calue4")

Does it make it more readable and should you do this? No

Warning, this will incorporate white-space between \ and the start of the next character.

2 Comments

Wait, there's something wrong with this, it logs false
Ah, the preceding whitespace was incorporated in the line since we escaped the newline.

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.