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 0
Add a ment  | 

2 Answers 2

Reset to default 8

You 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