JavaScript - Regular Expressions
Regular Expressions are a powerful way of matching patterns in text. They can get very complicated. This page introduces them with some simple initial examples.
First, some examples without regular expressions.
Replacing one string with another
You can use the replace
String method to replace one string with another.
var message = "Hello Planet!";
console.log(message); // Hello Planet!
message = message.replace("Planet", "World");
console.log(message); // Hello World!
The method matches the search string, "Planet", and replaces it with "World".
Only the first occurrence of the search string is replaced.
var message = "Hello Planet! You are a lovely Planet.";
console.log(message);
// Hello Planet! You are a lovely Planet.
message = message.replace("Planet", "World");
console.log(message);
// Hello World! You are a lovely Planet.
You can use a do...while
loop to replace all occurrences.
var message = "Hello Planet! You are a lovely Planet.";
console.log(message);
// Hello Planet! You are a lovely Planet.
do {
message = message.replace("Planet", "World");
} while (message.indexOf("Planet") !== -1)
console.log(message);
// Hello World! You are a lovely World.
Using a regular expression
The search string to be replaced can be specified by a regular expression. Rather than quotation marks as delimiters, regular expressions use forward slashes, /
.
var message = "Hello Planet! You are a lovely Planet.";
console.log(message);
// Hello Planet! You are a lovely Planet.
message = message.replace(/Planet/, "World");
console.log(message);
// Hello World! You are a lovely Planet.
To replace all occurrences of the search string, perform a global match by adding the g
flag after the closing delimiter.
var message = "Hello Planet! You are a lovely Planet.";
console.log(message);
// Hello Planet! You are a lovely Planet.
message = message.replace(/Planet/g, "World");
console.log(message);
// Hello World! You are a lovely World.
To ignore case, use the i
flag.
var message = "Hello Planet! You are a lovely planet.";
console.log(message);
// Hello Planet! You are a lovely planet.
message = message.replace(/Planet/ig, "World");
console.log(message);
// Hello World! You are a lovely World.
Not even scratching the surface
I know we haven't even scratched the surface of regular expressions. They can also use all kinds of special characters to specify exactly when, where and how text should be matched. Check out the Further Help to find out more.
Further Help
You can find an excellent reference on the Mozilla Developer Network Regular Expressions page.