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
}
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
}
if (/enable_my_feature/.test(window.location.href)) {
// execute conditional code
}
As you can see in JavaScript regular expressions start and end with a "/
".
.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
}
var myRegex = /(enable|disable)_my_feature/;
if (myRegex.test(window.location.href) {
// execute conditional code
}
A simple thing. We used regular expression syntax.
The elements we used are the brackets (
and )
and the pipe symbol |
.
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. |
What should a regex look like to match either "pancakes" or "fruitcakes"?
var myRegex = /(pan|fruit)cakes/;
What should a regex look like to match either "Hillary" or "Hillbilly"?
var myRegex = /Hill(ary|billy)/;
Cmd+Alt+J
(or F12
on Windows) to open console./http/.test(window.location.href)
More about brackets
More about the pipe symbol