2

I have this in my JavaScript,

alert(words.match(\b.(\w*)\b));

, where words is a string previously defined. But, the regex (\b.(\w*)\b) is producing a console error Uncaught SyntaxError: Unexpected token ILLEGAL. I think it's the backslashes, but no matter what I do, I still get the problem. I have thoroughly researched this problem on Stackoverflow and Google, but none of the results either works or meets my situation.

Here is the regex I am using: http://regexr.com?36u4v. Any held would be greatly appreciated.

1
  • Why has my question been voted down? Commented Oct 27, 2013 at 2:01

2 Answers 2

4

This comes down to "Is \b.(\w*)\b RegExp ?" Well, kind of, but you haven't told the interpreter that. It is not a RegExp literal in JavaScript. You need to either pass it as a String into the RegExp constructor, or use literal notation, which begins and ends with /

/\b.(\w*)\b/

As for your error, the interpreter reaches the \ first and does not know what this means, so it tells you that the token (\) was unexpected, so is "illegal" where you used it.


For multiple matches, you'll need to set the global flag, for example, to find "foo" multiple times

/foo/g

does this regex work well for selecting all words, excluding spaces and punctuation (other than underscores and hyphens)

\w is shorthand for the class [A-Za-z0-9_], so you're not matching hyphens at the moment. Your . will also match most characters including spaces and punctuation. You can swap the * (zero or more) for a + (one or more) so you don't need the .. Therefore the following may be more suitable for your needs

/\b([A-Za-z0-9_-]+)\b/g
Sign up to request clarification or add additional context in comments.

6 Comments

Okay, well that fixes the problem, with a nice explanation. But, now I am faced with another. This regex was supposed to select all words, excluding spaces and punctuation (other than underscores and hyphens), but now it's not doing that. On regexr, it was showing it working well, but now it's not.
Remember that . will match almost anything and that if you want multiple finds, you'll need to set the global flag.
Thanks. That seems to fix it.
It won't let me accept answer yet. By the way, does this regex work well for selecting all words, excluding spaces and punctuation (other than underscores and hyphens), or is there a better way?
@Mr.Shtuffs please see edit where I explain why, too
|
1

You forgot to put your regex literal into slashes:

alert(words.match(/\b.(\w*)\b/));

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.