admin管理员组文章数量:1319014
I'm trying to work out how to check a string for a specific word, and if that word exists set a new variable
I have the following jQuery code:
val= $('#' + this_id).val();
val can contain different strings of words.
I know I can do :
if (/Approve/i.test(val)) {
msg = "Approve"
}
But this also matches, Approved.. how do I match only Approve ? Ultimately I'm look to do :
if val contains Approve msg = "Approve"
if val contains Approved msg = "Approved"
if val contains Reject msg = "Rejected"
Thanks
I'm trying to work out how to check a string for a specific word, and if that word exists set a new variable
I have the following jQuery code:
val= $('#' + this_id).val();
val can contain different strings of words.
I know I can do :
if (/Approve/i.test(val)) {
msg = "Approve"
}
But this also matches, Approved.. how do I match only Approve ? Ultimately I'm look to do :
if val contains Approve msg = "Approve"
if val contains Approved msg = "Approved"
if val contains Reject msg = "Rejected"
Thanks
Share Improve this question edited Aug 3, 2015 at 14:18 blackpanther 11.5k12 gold badges52 silver badges79 bronze badges asked Aug 3, 2015 at 14:14 JeffVaderJeffVader 7022 gold badges17 silver badges33 bronze badges 02 Answers
Reset to default 8You can use word boundary (\b
):
if (/\bApprove\b/i.test(val)) {
msg = "Approve";
}
According to Regular expression tutorial - word boundary,
There are three different positions that qualify as word boundaries:
- Before the first character in the string, if the first character is a word character.
- After the last character in the string, if the last character is a word character.
- Between two characters in the string, where one is a word character and the other is not a word character.
Use this.
if (/^Approve$/i.test(val)) {
var msg = "Approve"
}
^
marks the start
$
marks the end
function check(val) {
var msg;
if (/^Approve$/i.test(val)) {
msg = "Approve";
} else if (/^Approved$/i.test(val)) {
msg = "Approved";
} else if (/^Reject$/i.test(val)) {
msg = "Rejected";
} else {
msg = "Error";
}
alert(msg);
}
check("Approve");
check("Approved");
check("Reject");
check("Hello");
本文标签: javascriptJquery regex test for exact word in stringStack Overflow
版权声明:本文标题:javascript - Jquery regex test for exact word in string - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742050544a2418042.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论