JavaScript · JS Functions & Objects · Lesson 45
JS RegExp
Search patterns with regular expressions.
A regular expression is a sequence of characters that forms a search pattern, written as /pattern/modifiers.
Example
<p id="demo"></p>
<script>
let text = "Visit Code Corner! Code is fun.";
let out = "";
out += "search: " + text.search(/corner/i) + "<br>";
out += "replace: " + text.replace(/code/gi, "HTML") + "<br>";
out += "test email: " + /^[^@\s]+@[^@\s]+\.[a-z]{2,}$/i.test("ada@example.com") + "<br>";
out += "match digits: " + "Call 555-1234 or 555-9876".match(/\d{3}-\d{4}/g);
document.getElementById("demo").innerHTML = out;
</script>
| Pattern | Meaning |
|---|---|
| i / g / m | Case-insensitive / global / multiline modifiers |
| \d / \w / \s | Digit / word character / whitespace |
| [abc] | Any of the characters |
| ^ and $ | Start and end of string |
| + * ? {n} | Quantifiers: 1+, 0+, 0 or 1, exactly n |
Keep reading “JS RegExp”
Sign up to read the full lesson, try every example in the live editor, and take the 5-question quiz.