转义要在正则表达式中使用的字符串

5年以前  |  阅读数:365 次  |  编程语言:JavaScript 

转义要在正则表达式中使用的字符串。

使用replace()可转义特殊字符。

const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
// escapeRegExp('(test)') -> \\(test\\)

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8