gpt4 book ai didi

javascript - 正则表达式查找字符串末尾的单词

转载 作者:行者123 更新时间:2023-11-28 15:30:42 25 4
gpt4 key购买 nike

我有字符串,根据该字符串的结束字符,我需要检查条件。我已经设法编写了以下脚本,但它没有按照我的预期进行。

//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”时,它会进入两种if情况。你能帮我解决这个问题吗?

最佳答案

您不需要 .* 选择器,因此您应该使用以下正则表达式

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

关于javascript - 正则表达式查找字符串末尾的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27504482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com