Regular Expressions will be more optimal for a lot of people because of word boundaries \b
or similar devices. Word boundaries occur when any of 0-9
, a-z
, A-Z
, _
are on that side of the next match, or when an alphanumeric character connects to line or string end or beginning.
if (location.href.match(/(?:\b|_)franky(?:\b|_)))
If you use if(window.location.href.indexOf("sam")
, you'll get matches for flotsam
and same
, among other words. tom
would match tomato and tomorrow, without regex.
Making it case-sensitive is as simple as removing the i
.
Further, adding other filters is as easy as
if (location.href.match(/(?:\b|_)(?:franky|bob|billy|john|steve)(?:\b|_)/i))
Let's talk about (?:\b|_)
. RegEx typically defines _
as a word character
so it doesn't cause a word boundary. We use this (?:\b|_)
to deal with this. To see if it either finds \b
or _
on either side of the string.
Other languages may need to use something like
if (location.href.match(/([^\wxxx]|^)(?:franky|bob|billy|john|steve)([^\wxxx]|$)/i))
//where xxx is a character representation (range or literal) of your language's alphanumeric characters.
All of this is easier than saying
var x = location.href // just used to shorten the code
x.indexOf("-sam-") || x.indexOf("-sam.") || x.indexOf(" sam,") || x.indexOf("/sam")...
// and other comparisons to see if the url ends with it
// more for other filters like frank and billy
Other languages' flavors of Regular Expressions support \p{L}
but javascript does not, which would make the task of detecting foreign characters much easier. Something like [^\p{L}](filters|in|any|alphabet)[^\p{L}]
"window.location.contains is not a function"