How to Check if a String Contains One of Multiple Values in JavaScript
To match a variable in JavaScript against multiple possible values, we can either use some
in combination with includes
in the following way:
Copied to clipboard! Playground
const blacklist = [
'suspicious-domain',
'untrusty-site',
'devious-page'
]
blacklist.some(item => document.location.href.includes(item))
Or if you need to match against a more complex pattern, then you can combine the elements of the array into a regex object and run a test against it like so:
Copied to clipboard! Playground
const blacklist = [
'suspicious-domain',
'untrusty-site',
'devious-page'
]
const regex = new RegExp(blacklist.join('|'), 'gi')
const isBlacklisted = regex.test(document.location.href)
Resources:
π More Webtips
Master the Art of Frontend
- Access 100+ interactive lessons
- Unlimited access to hundreds of tutorials
- Prepare for technical interviews