4

I have a line of code as follows

if($('#eqInputBox').val().search( $(this).html() ) == -1)

Which is supposed to check to see the html is already in the eqInputBox or not - problem is, sometimes the character in $(this).html() can be a '+' or a '*'. Any other character (in the set of possible characters for the app) works, but when these characters show up, the regular expression doesn't return any value - I think this might be because I can't slip a \ character in to escape these characters.

Anyone have any ideas on how, when the (this) html character is + or *, I can still make it check normally?


EDIT:

$(this).html()

is a user generated div, so I cannot simply put the escape character in manually. How would I go about dynamically adding it when it is necessary?

3
  • 1
    See this SO question. Commented Nov 22, 2011 at 6:18
  • Dave, that fixed it! Just replacing it with \\$1 that's exactly what I was looking for - thanks a lot! (Only problem is I can't mark this question as answered because you didn't post the response as an answer :-P) Commented Nov 22, 2011 at 7:25
  • Looks like $('#eqInputBox').val().indexOf($(this).html()) is enough. Commented Nov 22, 2011 at 11:07

3 Answers 3

3

You have to simulate quotemeta, have a look at Escaping regular expression

RegExp.escape = function(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is a very useful function to automatically escape characters - helps a lot, thanks!
2

The value of $(this).html() should be a valid Regular Expression pattern. In other words, instead of having d*, you should write \d* in it.

Thus you should escape characters statically, while creating the value of $(this).html().

Update: Since the value of $(this).html() is generated by user, you can create a helper function to detect special regular expression characters and escape it in that function.

function escapeCharacters(patter){
    // Here escape special characters. Eg. d* to \d*. However, it's difficulat
}

then use it this way:

if($('#eqInputBox').val().search( escapeCharacters($(this).html()) ) == -1)

1 Comment

You are right, the only problem is the $(this).html() is a user generated string, so it won't have the escape character when they enter it. Do you know any way to dynamically add this character to the RegExp at runtime?
1

MDN Docs suggest a slightly different regex than Toto answered:

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

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.