JavaScript - 在字符串匹配中使用变量 [英] JavaScript - Use variable in string match

查看:161
本文介绍了JavaScript - 在字符串匹配中使用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了几个类似的问题,但它没有帮助我...所以我有这个问题:

i found several similar questions, but it did not help me... so i have this problem:

var xxx = "victoria";
var yyy = "i";
alert(xxx.match(yyy/g).length);

我不知道如何在match命令中传递变量。请帮忙。谢谢。

I dont know how to pass variable in match command. Please help. Thank you.

推荐答案

虽然匹配函数不接受字符串文字作为正则表达式模式,但您可以使用RegExp的构造函数对象并将其传递给String.match函数:

Although the match function doesn't accept string literals as regex patterns, you can use the constructor of the RegExp object and pass that to the String.match function:

var re = new RegExp(yyy, 'g');
xxx.match(re);

您需要的任何标志(例如/ g)都可以进入第二个参数。

Any flags you need (such as /g) can go into the second parameter.

这篇关于JavaScript - 在字符串匹配中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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