Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a javascript regular expression escape character dynamically

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?

like image 303
Anthony Avatar asked Sep 02 '25 17:09

Anthony


2 Answers

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

RegExp.escape = function(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
like image 125
Toto Avatar answered Sep 04 '25 08:09

Toto


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)
like image 26
Saeed Neamati Avatar answered Sep 04 '25 07:09

Saeed Neamati