1

I have an issue in implementing Javascript RegExp - test Method.

var array = ['facebook', 'twitter', 'linkedin', 'xing', 'weibo']

array .forEach(function(cns) {
    var connector_name = '/.*' + cns + '$/';
    console.log('conne name', connector_name);
    if (connector_name.test('facebook')) {
        con = {
            account_type: cns
        };
        console.log('cns', cns);
    }

});

it gives me uncaughtException *** [TypeError: Object /.*facebook$/ has no method 'test']. but when i give following way it works

if (/.*facebook$/.test('facebook')) {
con = {
    account_type: 'facebook'
    };
}

Please help me to fix this issue. Thank you.

2 Answers 2

1

In your code:

var connector_name = '/.*' + cns + '$/';

There connector_name is a String, not a RegExp object. And String does not have the test() method.

But here:

if (/.*facebook$/.test('facebook')) {

/.*facebook$/ is a RegExp object, which has the test() method.

What you want to use is the RegExp constructor:

var array = ['facebook', 'twitter', 'linkedin', 'xing', 'weibo']

array .forEach(function(cns) {
    var connector_name = new RegExp('.*' + cns + '$');
    console.log('conne name', connector_name);
    if (connector_name.test(facebook)) {
        con = {
            account_type: cns
        };
        console.log('cns', cns);
    }

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

Comments

1

You can create a regular expression like this:

/regular expression/

… or like this:

new RegExp('regular expression')

You cannot create one using a string like this:

'/.*' + cns + '$/';

Snippet:

var array = ['facebook', 'twitter', 'linkedin', 'xing', 'weibo']

array .forEach(function(cns) {
  var connector_name = new RegExp('.*' + cns + '$');
  console.log('conne name', connector_name);
  if (connector_name.test('facebook')) {
    con = {
      account_type: cns
    };
    console.log('cns', cns);
  }
});

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.