Jeji
Jeji

Reputation: 31

Checking if a link contains a word in array javascript

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")
}

Upvotes: 3

Views: 1158

Answers (3)

Mohammad Usman
Mohammad Usman

Reputation: 39322

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");
}

Upvotes: 3

mohammed sadik vk
mohammed sadik vk

Reputation: 50

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");
}

Upvotes: 0

synthet1c
synthet1c

Reputation: 6282

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")
}

Upvotes: 4

Related Questions