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?
You have to simulate quotemeta
, have a look at Escaping regular expression
RegExp.escape = function(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With