如何将变量放入正则表达式匹配? [英] How to put variable in regular expression match?

查看:166
本文介绍了如何将变量放入正则表达式匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有

var string1 = 'asdgghjajakhakhdsadsafdgawerwweadf';
var string2 = 'a';
string1.match("\/"+string2+"\/g").length;

因此,我希望找到 a 的出现,但它是不是在逃,我怎么能把变量wright?

So with this i want to find the appereance of a, but itn is not wirking, how i can put the variable wright ?

推荐答案

你需要使用 RegExp 构造函数而不是正则表达式文字。

You need to use the RegExp constructor instead of a regex literal.

var string = 'asdgghjjkhkh';
var string2 = 'a';
var regex = new RegExp( string2, 'g' );
string.match(regex);

如果您不需要全局修饰符,那么您只需传递 string2 .match()将为您创建正则表达式。

If you didn't need the global modifier, then you could just pass string2, and .match() will create the regex for you.

string.match( string2 );

这篇关于如何将变量放入正则表达式匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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