Reputation: 9293
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.
Upvotes: 1
Views: 89
Reputation: 3816
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);
}
});
Upvotes: 1
Reputation: 35670
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);
}
});
Upvotes: 1