1

I have the next js code that checks some name in my url, but I can't figure how to check more than one. I want to verify six names if they appear in the url, and I don't want to type this code for 6 times.

Is there a way to introduce more than one name in the if line?

Thanks!

$(document).ready(function(){
    var urlSrtring = window.location.href;
    if (urlSrtring.indexOf('bogdan') !== -1) {
        alert('bb')
    }
} 
)

3 Answers 3

3

Use array.prototype.every:

var urlSrtring = "xyzlqksjdlkabclkqsjdiztuv";

var strs = ['xyz', 'abc', 'tuv']

if (strs.every(str => urlSrtring.indexOf(str) !== -1)) {
  console.log('OK');
}

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

1 Comment

includes is another alternative to indexOf :)
1

Use an array and a loop.

$(document).ready(function(){
    var wordsToFind = ["word1", "word2","word3", "word4","word5", "word6"];
    var urlSrtring = window.location.href;
    for(var k=0; k< wordsToFind.length; k++){
    if (urlSrtring.indexOf(wordsToFind[k]) != -1) {
        alert('bb')
    }
}
} 

)

Comments

0

You can use an Array with the names and execute either the forEach function or vanilla Javascript for-loop.

var names = ["nippets", "net", "Jeff"];

var urlSrtring = window.location.href;
console.log(urlSrtring);
names.forEach(function(name) {
  if (urlSrtring.indexOf(name) !== -1) {
    console.log('bb');
  }
});

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.