Animations

API

Arrays

Async

Basics

Challenges

Classes

Console

Dates

Debugging

DOM Elements

DOM Methods

DOM Navigation

DOM Properties

Event Listeners

Flow Control

Forms

Functions

Global Functions

JSON

Keywords

Libraries (3rd party)

Math

Modules

Objects

Snippets

String

Types

Widgets

Window Object

JavaScript - RegEx Example

This page will show a increasingly complex example. We will start simple and grow it's complexity.

And.... Introduce a little anarchy, upset the established order and everything becomes chaos. I'm an agent of chaos. Oh, and you know the thing about chaos? It's fair. - The Dark Knight, 2008

Looking for anarchy regardless of case. Will return position. This is a literal search.


// example 1
let pattern1 = /Anarchy/i;
let results1 = stringToSearch.search(pattern1);
document.getElementById("demo1").innerHTML = "Position of Anarchy: " + results1;


This uses a range. In this example, we are looking for any characters from a to z. The asterisk indicates we are looking for a match with any number of characters - starting at 1. The results are 0 as expected. It found a match in position "0".


// example 2
let pattern2 = /[a-z]*/i;
let results2 = stringToSearch.search(pattern2);
document.getElementById("demo2").innerHTML = results2;


This looks for a range of characters from a-z but will require the match which is found have 7 characters. This is done by using the {7} instead of the *.


let pattern3 = /[a-z]{7}/i;
let results3 = stringToSearch.search(pattern3);
document.getElementById("demo3").innerHTML = results3;


This example uses \b modifiers. This requires the match to be on a string boundary - it must be on the beginning of the string and/or the end of the string. Here, we are looking for the string 'thing' which must be in the beginning of the string or the end.


let pattern4 = /\bthing\b/i;
let results4 = stringToSearch.search(pattern4);
document.getElementById("demo4").innerHTML = results4;


This example uses a numeric range [0-9] and requires four characters. The match must be at the beginning or the end of the string.


let pattern5 = /\b[0-9]{4}\b/;
let results5 = stringToSearch.search(pattern5);
document.getElementById("demo5").innerHTML = results5;


This example uses a numeric range [0-9] and requires five characters which is common for finding a zipcode. In addition, it allows for a user or input to provide a plus-four zipcode. Since the input may or may not have the plus-four part, we need to account for that.


// example 6 - couldn't get this to work...
let stringToSearch2 = "My zip code is 23112-0000.";
let pattern6 = /\b[0-9]{5}(?:-[0-9]{4})?\b/;
let results6 = stringToSearch.search(pattern6);
document.getElementById("demo6").innerHTML = results6;

 

https://www.w3schools.com/js/js_regexp.asp

http://buildregex.com/

https://www.regexbuddy.com/create.html