JavaScript Search for Lines Beginning with a Word
From Regex Regular Expression Encyclopedia
This recipe allows you to find whole words at the beginning of a line.
[edit] code
<html> <head> <title></title> </head> <body> <form name="form1"> <input type="textbox" name="txtInput" /> <script type="text/javascript"> function validate() { if (! document.form1.txtInput.value.match(/^Word\b/)) { alert("Please enter valid value!") } else { alert("Success!") } } </script> <input type="button" name="btnSubmit" onclick="validate()" value="Go" /> </form> </body> </html>
[edit] How It Works
The key to this expression is the line anchor metacharacter ^. You can break the expression down like this:
| Regular Expression | Description |
|---|---|
| ^ | at the start of the line, followed immediately by . . . |
| W | then . . . |
| o | followed by . . . |
| r | then . . . |
| d | and lastly . . . |
| \b | a word boundary. |
The \b character class is an anchor like the ^ line anchor. However, \b is a word anchor, and the ^ metacharacter is a line anchor.
