Reputation: 9303
I have string, based on the end character of that string I need to check a condition. I have managed to write following script, but its not taking as I intended.
//var receivers_type = "d2845a48f91b29f9d0a6e96858f05d85xing";
var receivers_type = "d21fca8635940e97d0f8e132d806cedaxingpage";
if (/.*xing/.test(receivers_type)) {
console.log('xing profile');
flag = 1;
}
if (/.*xingpage/.test(receivers_type)) {
console.log('xing page');
flag = 0;
}
when receivers_type = "d2845a48f91b29f9d0a6e96858f05d85xing"
condition is working properly. it will only enter into first if loop. But when the receivers_type = "d21fca8635940e97d0f8e132d806cedaxingpage"
it is entering in to both if cases. Could you help me to solve this issue.
Upvotes: 0
Views: 63
Reputation: 1736
I recommend to use following expression:
/xingpage$/
So you would have:
if (/xingpage$/.test(receivers_type)) {
console.log('xing page');
flag = 0;
}
Upvotes: 0
Reputation: 17795
You need to match the end of the string in your regex.
You can do this using the "end of string anchor", which is a dollar character.
var receivers_type = "d21fca8635940e97d0f8e132d806cedaxingpage";
if (/.*xing$/.test(receivers_type)) {
console.log('xing profile');
}
if (/.*xingpage$/.test(receivers_type)) {
console.log('xing page');
}
You can read more here: http://www.regular-expressions.info/anchors.html
Upvotes: 1
Reputation: 3200
You don't need the .*
selector, so you should use the folowing regexp
/xing$/ <-- the character $ means that the xing must be at the end of the string
So your code will be:
//var receivers_type = "d2845a48f91b29f9d0a6e96858f05d85xing";
var receivers_type = "d21fca8635940e97d0f8e132d806cedaxingpage";
if (/xing$/.test(receivers_type)) {
console.log('xing profile');
flag = 1;
}
if (/xingpage$/.test(receivers_type)) {
console.log('xing page');
flag = 0;
}
Upvotes: 3
Reputation: 136
Use match in Javascript and change the regex:
if(recievers_type.match(/(xingpage)$/)
Upvotes: 0