1

I'm dealing with a really long regex pattern to match on and it's so long I'm going to have to split it up into several different strings. My question is: How can I avoid the escape characters in JavaScript to instantiate a new RegExp to create a testable pattern?

In C# it's pretty simple: Just suffice the string with the @ symbol and the compiler takes care of it. JavaScript is totally different and I'm not certain what the equivalent statement is.

8
  • 1
    Use a regex literal notation, /\w+/. Then, you'd need to call the .source property to access the pattern itself for concatenation (/\w+/.source + /\s+/.source). Commented Nov 14, 2016 at 22:52
  • The forward slash is what i am trying to avoid. It's an "escape character" Commented Nov 14, 2016 at 22:53
  • Can you provide this regex? Commented Nov 14, 2016 at 22:53
  • @user1789573: You do not understand that /.../ are not escaping characters, these are regex delimiters. Commented Nov 14, 2016 at 22:54
  • You alse can simplify your regexp, e.g. (\s?\s?\s?\s?) == (\s{0,4}) ; (\s{0,4})? == (\s{0,4}) etc Commented Nov 14, 2016 at 23:03

1 Answer 1

1

You may use a regex literal notation, e.g. /\w+/. Then, you'd need to call the .source property to access the pattern itself for concatenation purposes, e.g. /\w+/.source + /\s+/.source.

See more details about using RegExp at MDN.

Personally, I'd rather build a pattern from string blocks, where \ should be doubled (e.g. var word = "\\w+"; var spaces = "\\s+"; var pattern = word + spaces;. This way, the overhead related to regex object construction will be avoided. It is up to you to choose the most convenient approach.

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

Comments

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.