How to Check if a String Contains One of Multiple Values in JavaScript

How to Check if a String Contains One of Multiple Values in JavaScript

Ferenc Almasi β€’ 2022 January 12 β€’ Read time 1 min read
  • twitter
  • facebook
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)
How to Check if a String Contains One of Multiple Values in JavaScript 
If you would like to see more webtips, follow @flowforfrank

50 JavaScript Interview Questions

Resources:

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

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:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.