如何动态添加javascript正则表达式转义字符 [英] How to add a javascript regular expression escape character dynamically

查看:233
本文介绍了如何动态添加javascript正则表达式转义字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一行代码如下

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

应该检查哪个看到html已经在eqInputBox中了 - 问题是,有时 $(this).html()中的字符可以是'+ ''*'。任何其他角色(在应用程序的可能字符集中)都有效,但是当这些角色出现时,正则表达式不会返回任何值 - 我想这可能是因为我无法使用 \ 要转义这些字符的字符。

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.

任何人对于(此)html字符<$ c时的方式有任何想法$ c> + 或 * ,我还能正常检查吗?

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

编辑:

$(this).html()

是用户生成的 div ,所以我不能简单地手动放置转义字符。如果有必要,我该如何动态添加?

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?

推荐答案

你必须模拟 quotemeta ,请查看转义正则表达式

RegExp.escape = function(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}

这篇关于如何动态添加javascript正则表达式转义字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆