0
<form name="form1">
<input type="textbox" name="txtInput" />
<script type="text/javascript">
function validate() {
if (! document.form1.txtInput.value.match(/\bSun(il)? (Mishra)?\b/)){
    alert("Please enter valid value!");
} else {
    alert("Success!");
}
}
</script>
<input type="button" name="btnSubmit" onclick="validate()" value="Go" />

It gives success on Sunil Mishra, Sun Mishra but not for Sunil OR Sun. I tried entering the input with space, but that also doesn't work.

Is there some issue in the code?

1
  • remove the blank space Commented Jun 7, 2013 at 13:01

3 Answers 3

4

If the space is optional, it needs to be in the second group too:

/\bSun(il)?( Mishra)?\b/

The reason adding a space at the end won’t work is because there’s no word boundary (\b) at the end of a string after a space.

Sign up to request clarification or add additional context in comments.

Comments

1
/\bSun(il)? (Mishra)?\b/

The reason this doesn't match Sun or Sunil on its own without Mishra is because of the space between the two names in the regex pattern.

The space isn't shown as optional, so the pattern will fail to match if the space isn't present, even though Mishra is optional.

To fix this, move the brackets around Mishra to include the space before it:

/\bSun(il)?( Mishra)?\b/

1 Comment

The pattern will not work even if space is added as pointed by minitech
0

Rather than having to add the space into the second group, as the other answers have pointed out, you can use: /\bSun(il)?\s*(Mishra)?\b/. This will allow more than one space, tabs, etc. while also keeping it out of the Mishra group's result.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.