Regular Expressions in JavaScript

guosae

Guosa

Posted on July 28, 2020

Regular Expressions in JavaScript

In JavaScript there are two ways to create regular expressions.

In the first way, one can write a pattern of letters, numbers or symbols enclosed in forward slash(/) characters, like so:

let regex1 = /xyz123/;

When using this first method of constructing regular expressions, certain special characters, like a question mark(?), asterisk/star(*), dollar sign($), vertical pipe symbol (|), period/dot (.), opening or closing parenthesis, and certain other special characters, need to have a back slash ( \ ) before their character in order be included in the pattern that the regular expression is searching for, as in the following cases:

let regex1question = /xyz123\?/;

let regex1pipe = /xyz123\|/;

let regex1money = /xyz123\$/;

In the second method of constructing regular expressions, one can use the RegExp constructor:

new RegExp()

With the RegExp constructor, one encloses the pattern of letters, numbers or symbols in quotation marks, like a string, within parentheses:

let regex2 = new RegExp("xyz123");

let regex2money = new RegExp("xyz123$")

A regular expression object in JavaScript has methods that can be used on it. For example, the method test returns a Boolean which indicates whether the string passed as an argument in the test method matches the pattern of the regular expression. For example:

console.log(/123xyz/.test("123xyz456"));

will return true since the pattern "123xyz" is contained in the string "123xyz456".

On the other hand the following:

console.log(/123xyz/.test("123zzz456"));

will return false, since the pattern "123xyz" is not contained in the string "123zzz456".

However, if we want to test whether or not a string contains any of the characters in a pattern, we can put the characters in regular expression between square brackets, as in the following:

console.log(/[123xyz]/.test("zzz"));

This will return true, since the string "zzz" does contain the character "z" from the pattern "123xyz".

We can also use certain shortcuts to indicate if we are searching for a certain type of character. For example,

\d indicates any character that is a digit between 0 and 9 (inclusive).

\w indicates any alphanumeric character

\W indicates any non-alphanumeric character

\D indicates any number that is not a digit

Further reading:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/RegExp

💖 💪 🙅 🚩
guosae
Guosa

Posted on July 28, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related