js正则表达式向后兼容标志 [英] js regex backwards compatibility of flags

查看:150
本文介绍了js正则表达式向后兼容标志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些在最新浏览器中运行时运行良好的正则表达式。它具有以下形式:

I have a some regex that works perfectly when running inside up-to-date browsers. It is of the following form:

var re = new RegExp(/(somePattern)/,'g');

它在旧版Chrome上引发错误,错误是:

It throws an error on older versions of chrome, the error is that:


从另一个构建一个RegExp时无法提供标志

"can't supply flags when constructing one RegExp from another"

根据 MDN 的文档:


从ECMAScript 6开始,新的RegExp(/ ab + c /,'i')不再抛出TypeError(无法提供当第一个参数是RegExp并且存在第二个flags参数时,从另一个)构造一个RegExp时标记。而是创建了一个来自参数的新RegExp。

Starting with ECMAScript 6, new RegExp(/ab+c/, 'i') no longer throws a TypeError ("can't supply flags when constructing one RegExp from another") when the first argument is a RegExp and the second flags argument is present. A new RegExp from the arguments is created instead.

我不完全明白这意味着什么。如何更改上面的正则表达式以避免错误?

I don't exactly understand what that means. How can I alter the regex above to avoid the error?

推荐答案

您已经在使用正则表达式文字。

You are already using a regex literal.

var reg = /abc/g;

这是一个有效的正则表达式。

That's a valid regular expression.

如果你要使用构造函数(不要,除非你有充分的理由),你应该传递一个字符串,而不是正则表达式。

If you were to use the constructor (don't, unless you have good reason to), you should be passing it a string, and not a regex.

new RegExp("abc", "g");

MDN参考

这篇关于js正则表达式向后兼容标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆