I've got the following regex which looks for a match of abc
inside def
:
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?
答案 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');