JavaScript Search for Lines Ending with a Word

From Regex Regular Expression Encyclopedia

Jump to: navigation, search

This recipe finds full words at the end of a line. For the purposes of this example, that word is finale.

[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(/\bfinale$/)) {
				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 use of character classes. Two of them are used, one to define the end of the line and one to define a word boundary, so you get only whole words when using the expression. You can break the regular expression down like this:

Regular Expression Description
\b is a word boundary, such as a space, tab, and so on, followed by . . .
finale f, i, n, a, l, followed by e and lastly . . .
$ the end of the line.

The line anchor $ is like the line anchor ^ because both of them are supported in nearly every flavor of regular expression. The “Syntax Overview” section at the beginning of this book highlights the different character classes supported in the various sections of regular expressions.

[edit] Variations

You may be interested in matching lines where the word is the last word on the line, which means spaces may appear between the end of the word and the end of the line. To modify the expression to match lines with possible spaces, use the character class that matches spaces with the * qualifier, which matches none or many. The regular expression variation looks like this: \bfinale\s*$.

Personal tools