Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
123 views
in Technique[技术] by (71.8m points)

javascript - Javascript中是否存在RegExp.escape函数?(Is there a RegExp.escape function in Javascript?)

I just want to create a regular expression out of any possible string.(我只想从任何可能的字符串中创建一个正则表达式。)

var usersString = "Hello?!*`~World()[]"; var expression = new RegExp(RegExp.escape(usersString)) var matches = "Hello".match(expression); Is there a built in method for that?(有内置的方法吗?) If not, what do people use?(如果没有,人们会使用什么?) Ruby has RegExp.escape .(Ruby具有RegExp.escape 。) I don't feel like I'd need to write my own, there's gotta be something standard out there.(我觉得我不需要自己写东西,那里肯定有一些标准。) Thanks!(谢谢!)   ask by Lance Pollard translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The function linked above is insufficient.(上面链接的功能不足。)

It fails to escape ^ or $ (start and end of string), or - , which in a character group is used for ranges.(它无法转义^$ (字符串的开头和结尾)或- ,这在字符组中用于范围。) Use this function:(使用此功能:) RegExp.escape= function(s) { return s.replace(/[-/\^$*+?.()|[]{}]/g, '\$&'); }; While it may seem unnecessary at first glance, escaping - (as well as ^ ) makes the function suitable for escaping characters to be inserted into a character class as well as the body of the regex.(乍看起来似乎没有必要,但转义- (以及^ )使该函数适合于转义要插入字符类和正则表达式主体的字符。) Escaping / makes the function suitable for escaping characters to be used in a JS regex literal for later eval.(转义/使该函数适合转义要在JS regex文字中使用的字符,以供以后评估。) As there is no downside to escaping either of them it makes sense to escape to cover wider use cases.(由于逃避任何一个都没有不利之处,因此有理由逃避以涵盖更广泛的用例。) And yes, it is a disappointing failing that this is not part of standard JavaScript.(是的,如果它不是标准JavaScript的一部分,这是令人失望的。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...