Regex with dynamic variable not working

时间:2015-10-06 08:21:31

标签: javascript

I've got the following regex which looks for a match of abc inside def:

http://jsfiddle.net/82hyrpoL/

var abc = 'foo',
    def = '123456789qwertyuifoobar23rghfj';

if( def.match('/' + abc + '/i') ){
    console.log('DONE!');
} else {
    console.log('ERROR!');
}

But it isn't returning true. Why? What am I doing wrong?

2 个答案:

答案 0 :(得分:2)

You will have to create a regular expression by using the RegExp object:

var abc = 'foo',
    def = '123456789qwertyuifoobar23rghfj',
    rgexp = new RegExp(abc, 'i');

if( def.match(rgexp) ){
    console.log('DONE!');
} else {
    console.log('ERROR!');
}

Or (even more compact):

var abc = 'foo',
    def = '123456789qwertyuifoobar23rghfj';

if( new RegExp(abc, 'i').test( def ) ){
  console.log('DONE!');
} else {
  console.log('ERROR!');
}

Regular expressions are not normal strings.

答案 1 :(得分:1)

Using test() of RegExp https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test

var abc = /foo/i,
def = '123456789qwertyuifoobar23rghfj';

if (abc.test(def))
    alert('true');
else
    alert('false'); 
相关问题