3

How to check if a link contains a word in array?

var substrings = ['connect', 'ready','gmanetwork'];
var str = window.location.href
if (substrings.some(function(v) { return str === v; })) {
   alert("true")
}

3 Answers 3

4

I would use str.indexOf(v) > -1 to check if the href contains the word in your array.

If you want to be one of the cool kids you can use the Bitwise NOT like this. ~str.indexOf(v)

var substrings = ['connect', 'ready','gmanetwork'];
// var str = window.location.href
var str = 'somethingconnect.com'
if (substrings.some(function(v) { return str.indexOf(v) > -1 })) {
   console.log("true")
}

Sign up to request clarification or add additional context in comments.

2 Comments

yes, let's be cool kids and ~str.indexOf(v). For the one who does not know: check MDN ~ Bitwise NOT Reference developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
Never heard of bitwise before but thankfully it worked :)
3

You may use:

As from Docs:

The includes() method determines whether one string may be found within another string, returning true or false as appropriate.

Example:

const substrings = ['connect', 'ready','gmanetwork'];
const str = 'gmanetwork.com';

if(substrings.some(s => str.includes(s))) {
  console.log("Value exists");
}

Comments

0

var substrings = ['connect', 'ready','gmanetwork'];
var str = 'http://www.example.com/connect-your-pc'; //url

if (substrings.some(function(v) { return str.indexOf(v) >= 0; })) {
   alert("true");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.