1

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 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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'); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.