Escape a '+' plus sign in a string to be u

2019-07-11 03:06发布

This question already has an answer here:

I have a regex I'm running to filter rows in a table. The filtering is done in Javascript.

I'm writing coffeescript, but a Javascript solution would be fine -- I can just translate it to coffeescript myself.

I have a value role that contains a string I want to filter on using a regex. The problem is the string role may or may not have embedded '+' signs in it. Plus signs are special characters for regex searches and need to be escaped in the search string.

I create the regex search string like this (coffeescript):

"^"+role+"$"

How can I preprocess role to escape any '+' signs so the regex works?

1条回答
做个烂人
2楼-- · 2019-07-11 03:43

+ is far from the only character with special meaning. Here is a function that will escape all the necessary characters:

function regex_escape(str) {
    return str.replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\-]', 'g'), '\\$&');
}
查看更多
登录 后发表回答