How can I check if within one string there are others?

Asked

Viewed 60 times

0

In javascript, I want to check if in a string there is at least one of the following strings: . com, . edu, . br, etc... if one of these strings exists in the main string, I want it to come back true.

2 answers

0


You can use the method indexOfto check if one of these words is located in the string passed.

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; where the reference does not exist indexOf will return -1

To move 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

0

To do this check you can use the method index of String

This method is case sensitive (so we change the string and search key to uppercase), returns -1 when it does not find the key to search otherwise returns the first position where the key was found.

https://developer.mozilla.org/pt-PT/search?q=uppercase

const url = "omeusite.edu";

const chave = "edu";

if (url.toUpperCase().indexOf(chave.toUpperCase()) > -1) {
  alert("A chave foi encontrada!")
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.