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
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: