LMH
LMH

Reputation: 949

Javascript RegExp: Word boundaries and punctuation marks

Im trying to use javascript's RegExp to match full words but it doesn't work when those words have punctuation as the boundary. I.e.

(new RegExp("\\b"+RegExp.escape("why not")+"\\b", 'i')).test("why not you foolish")

Correctly matches. And:

(new RegExp("\\b"+RegExp.escape("why not")+"\\b", 'i')).test("why nots you foolish")

Correctly does not match. The problem is this doesn't work when the word ends with a "?":

(new RegExp("\\b"+RegExp.escape("why not?")+"\\b", 'i')).test("why not? you foolish") 

Any suggestions?

NOTE: I am using this function to escape:

# Escape characters for regexp
RegExp.escape = (text) ->
  text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")

Upvotes: 2

Views: 3513

Answers (2)

kirilloid
kirilloid

Reputation: 14304

? has a special meaning in RegExp and should be escaped.

Ok, I see, you're trying to escape it... but not all browsers have this method RegExp.escape built-in and it seemed, this is the prolbem. Cause

(new RegExp("\\b"+"why not\?"+"\\b", 'i')).test("why not? you foolish")

works as supposed (return true).

Here's a code I used:

if (typeof RegExp.escape == "undefined") {
    RegExp.escape = function(str) {
        return str.replace(/([()\[\]\\\/+*?.-])/g, "\\$1");
    }
}

Upvotes: 3

bryanjonker
bryanjonker

Reputation: 3406

"?" is a special character for Regex. I believe you need to escape it.

Upvotes: 1

Related Questions