栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在JavaScript中使用动态(可变)字符串作为正则表达式模式

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在JavaScript中使用动态(可变)字符串作为正则表达式模式

要从字符串创建正则表达式,必须使用Javascript的

RegExp
object。

如果你也想匹配/替换超过一次,那么你就 必须添加的

g
(全局匹配)标志。这是一个例子:

var stringToGoIntoTheRegex = "abc";var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");// at this point, the line above is the same as: var regex = /#abc#/g;var input = "Hello this is #abc# some #abc# stuff.";var output = input.replace(regex, "!!");alert(output); // Hello this is !! some !! stuff.

在一般情况下,在用作正则表达式前先对字符串进行转义:

但是,并非每个字符串都是有效的正则表达式:有些特殊字符,例如

(
[
。要变通解决此问题,只需将字符串转为正则表达式之前先对其进行转义。下面的示例中包含一个实用程序功能:

function escapeRegExp(stringToGoIntoTheRegex) {    return stringToGoIntoTheRegex.replace(/[-/\^$*+?.()|[]{}]/g, '\$&');}var stringToGoIntoTheRegex = escapeRegExp("abc"); // this is the only change from abovevar regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");// at this point, the line above is the same as: var regex = /#abc#/g;var input = "Hello this is #abc# some #abc# stuff.";var output = input.replace(regex, "!!");alert(output); // Hello this is !! some !! stuff.

注意:问题中的正则表达式使用

s
修饰符,该修饰符在提问时并不存在 ,但今天确实存在 -Javascript中
s
dotall)标志/修饰符。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/420692.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号