In javascript, I want to check on a string for at least one of the other strings: .com, .edu, .uk, etc ... if one of these strings exist in the main string, I want to return true.
In javascript, I want to check on a string for at least one of the other strings: .com, .edu, .uk, etc ... if one of these strings exist in the main string, I want to return true.
You can use the indexOf
method to check if one of these words is located in the last string.
let palavras = ".org, .edu, .edu";
console.log(palavras.indexOf(".org"));
In this example the return will be 0
the current position of the word .org
; if the reference does not exist indexOf
will return -1
To pass to a function just check the return
let palavras = ".org, .edu, .edu";
function verificaOcorrencias(sequencia, palavra){
if(sequencia.indexOf(palavra) !== -1){
return true;
}else{
return false;
}
}
console.log(verificaOcorrencias(palavras, ".org")); //true
console.log(verificaOcorrencias(palavras, "algo")); //false
To do this check you can use the indexOf method of String
This method is case sensitive (so we changed the string and search key to uppercase), returns -1 when it does not find the key to search for otherwise returns the first position where the key was found.
const url = "omeusite.edu";
const chave = "edu";
if (url.toUpperCase().indexOf(chave.toUpperCase()) > -1) {
alert("A chave foi encontrada!")
}