Regular Expressions (often shortened to "regex" or "regexp") is a sequence of characters specifying a search pattern. This allows you to look for strings, either simply to test if they are there, to extract them for use elsewhere, or to perform search/replace operations.
Defining a regular expression
But first, let's see how a regular expression might look:
let regex = /[0-9]+/;
let regex = new RegExp("[0-9]+");
Using the regular expression
Obviously, just creating a RegExp object doesn't get us anywhere - we have to use one of the helpful methods. One of the simplest method is the test() method - it will simply tell you if a match can be made using the regular expression against a string. Here's an example:
let testString = "Hello, I'm 42 years old"; let regex = new RegExp("[0-9]+"); if(regex.test(testString)) alert("String contains a number!"); else alert("String does NOT contain a number!");
Using Regular Expressions (regex), you can define a search pattern and then perform search and search/replace operations on a string. Regular expressions are almost like a mini-programming language and can be quite complex and extremely versatile.