Sunil Mishra
Sunil Mishra

Reputation: 3826

Javascript regular expression unexpected results

<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?

Upvotes: 0

Views: 75

Answers (3)

Sly
Sly

Reputation: 1165

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.

Upvotes: 0

Spudley
Spudley

Reputation: 168665

/\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/

Upvotes: 1

Ry-
Ry-

Reputation: 224877

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.

Upvotes: 4

Related Questions