正则表达式,用于在字符串末尾查找单词(Regular expression to find a word at the end of the string)

我有字符串,基于该字符串的结束字符,我需要检查一个条件。 我已设法编写以下脚本,但它没有按照我的意图。

//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; }

当receivers_type = "d2845a48f91b29f9d0a6e96858f05d85xing"条件正常工作时。 它只会进入第一个if循环。 但是当receivers_type = "d21fca8635940e97d0f8e132d806cedaxingpage" ,如果是这种情况,它将进入两者。 你能帮我解决这个问题吗?

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.

最满意答案

你不需要.*选择器,所以你应该使用下面的正则表达式

/xing$/ <-- the character $ means that the xing must be at the end of the string

所以你的代码将是:

//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; }

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; }

更多推荐