html转义符 npm,用于Javascript regex的转义字符串

短甜function escapeRegExp(string) {

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

例escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");

>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "

安装npm install --save escape-string-regexp

其他符号(~`!@#.)可以逃脱而没有后果,但不需要这样做。

.

.

.

.

测试用例:典型的urlescapeRegExp("/path/to/resource.html?search=query");>>> "\/path\/to\/resource\.html\?search=query"

长篇大论

如果要使用上面的函数,至少要链接到代码文档中的堆栈溢出帖子,这样就不会让它看起来像疯狂的、难以测试的巫毒。var escapeRegExp;(function () {

// Referring to the table here:

// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp

// these characters should be escaped

// \ ^ $ * + ? . ( ) | { } [ ]

// These characters only have special meaning inside of brackets

// they do not need to be escaped, but they MAY be escaped

// without any adverse effects (to the best of my knowledge and casual testing)

// : ! , =

// my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)

var specials = [

// order matters for these

"-"

, "["

, "]"

// order doesn't matter for any of these

, "/"

, "{"

, "}"

, "("

, ")"

, "*"

, "+"

, "?"

, "."

, "\\"

, "^"

, "$"

, "|"

]

// I choose to escape every character with '\'

// even though only some strictly require it when inside of []

, regex = RegExp('[' + specials.join('\\') + ']', 'g')

;

escapeRegExp = function (str) {

return str.replace(regex, "\\$&");

};

// test escapeRegExp("/path/to/res?search=this.that")}());

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值