Skip to content

Latest commit

 

History

History
33 lines (20 loc) · 969 Bytes

escape-reg-exp.md

File metadata and controls

33 lines (20 loc) · 969 Bytes
标题 标签
escapeRegExp(转义正则表达式) string,regexp(字符串,正则表达式)

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

  • 使用 String.prototype.replace() 转义特殊字符。

代码如下:

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

ts 代码如下:

调用方式:

escapeRegExp("(test)"); // \\(test\\)

应用场景

以下是一个实战示例:

结果如下:

<iframe src="codes/javascript/html/escape-reg-exp.html"></iframe>