HTML Dog
Skip to navigation

Regular Expressions

Regular expressions are another type of data in JavaScript, used to search and match strings to identify if a string is a valid domain name or to replace all instances of a word within a string, for example.

Creating regular expressions

Like with objects and arrays, there is a regular expression literal syntax designated by two forward slashes. Everything between is the expression:


var regex = /^[a-z\s]+$/;

This expression matches strings that are made of lowercase letters and whitespace from beginning to end. The caret (“^”) indicates the start of the string, and the brackets indicate that anything between the opening and closing brace - letter a to z (“a-z”), lowercase, and white-space, indicated by the special “\s” character - can be repeated one or more times up to the end of the string, indicated by the dollar (“$”) symbol.

Strings have a few useful methods that accept regular expressions; here’s a look at match and replace:


var lowerCaseString = 'some characters';

if (lowerCaseString.match(regex)) {
    alert('Yes, all lowercase');
}

match produces a truthy value if the regular expression matches the string (lowerCaseString) match is called on. The string matches, so execution drops into the if statement to show an alert.

Regular expressions can also be used to replace text:


var text = "There is everything and nothing.";

text = text.replace(/(every|no)thing/g, 'something');

// text is now "something and something"

This expression matches the word “everything” and the word “nothing” and replaces all occurrences of them with the word “something”. Notice the “g” after the closing forward slash (“/”) of the regular expression - this is the global flag that means the expression should match all occurrences, rather than just the first, which is what it does by default.

Flags always go after the closing slash. The other flag you might need to use is the case-insensitive flag. By default, regular expressions care about the difference between uppercase and lowercase letters, but this can be changed using the “i” flag.


var text = "Everything and nothing.";

text = text.replace(/(every|no)thing/gi, "something");

// text is now "something and something"