String matches with regular expressions

Let's get started...

Let's say you have this URL and you want to check if it contains the string "enable_my_feature"

https://www.example.com/page.html?enable_my_feature

Maybe you are used to doing something like this (it will work perfectly fine):

if (window.location.href.indexOf("enable_my_feature") > -1) { // will evaluate to true
    // execute your conditional code
}

This is how RegEx does it

To test for a string we use the .test() method:

var myRegex = /enable_my_feature/;
if (myRegex.test(window.location.href)) { // will return true
    // execute conditional code
}

Same but shorter:

if (/enable_my_feature/.test(window.location.href)) {
    // execute conditional code
}

As you can see in JavaScript regular expressions start and end with a "/".


So why should I use a RegEx and not .indexOf()?

You are right. For the above example, there is hardly any advantage (except maybe brevity). But let's now look at the strength of RegExes.

Let's say you want to know if the URL contains either the parameter "enable_my_feature" or "disable_my_feature".

This becomes cumbersome with the use of .indexOf():

if (window.location.href.indexOf("enable_my_feature") > -1
    || window.location.href.indexOf("disable_my_feature") > -1) {
    // execute conditional code
}

Compare to this (RegEx magic):

var myRegex = /(enable|disable)_my_feature/;
if (myRegex.test(window.location.href) {
    // execute conditional code    
}

What has happened here?

A simple thing. We used regular expression syntax.
The elements we used are the brackets ( and ) and the pipe symbol |.

What do they do?

Element Purpose
Brackets () Brackets are used to group parts of a RegEx. This is necessary in our case for our "either/or" group.
Pipe symbol | The pipe symbol is the "or" symbol of regular expressions. In our case one of the strings has to match in order for the entire regular expression to match.

Exercise 1

What should a regex look like to match either "pancakes" or "fruitcakes"?

Solution (click to reveal)

var myRegex = /(pan|fruit)cakes/;

Exercise 2

What should a regex look like to match either "Hillary" or "Hillbilly"?

Solution (click to reveal)

var myRegex = /Hill(ary|billy)/;

Practical exercise

  1. Press Cmd+Alt+J (or F12 on Windows) to open console.
  2. Type this: /http/.test(window.location.href)
  3. Press enter - it should return "true".
  4. Now create your own Regex and test it on window.location.href
  5. Now use an either/or match (with pipe symbol).

Click here for your reward

Congratulations! You learned a great deal about RegExes today.

Further reading

More about brackets
More about the pipe symbol


Was this page helpful?

Thank you for telling