Uncategorized

Como saber se há uma substring dentro de uma string em JavaScript

O JavaScript é uma das linguagens de programação mais fáceis de aprender. Se você está confuso sobre como verificar se uma string contém outra substring em JavaScript, então você chegou ao lugar certo. Há muitas maneiras de verificar isso, então vamos ver cada uma.

string.indexOf()

A melhor maneira de encontrar uma substring de uma string é usar a função indexOf(). Se você notou, o método indexOf() simplesmente testa se a substring está presente ou não. Se estiver presente, ele retornará o índice inicial da substring; Se não, ele retornará -1. Podemos usar o comportamento do método indexOf() para encontrar uma substring. Tudo o que precisamos fazer é definir uma condição para verificar o valor de retorno.

var programminglanguages = "C++, JavaScript, Ruby";


var newlanguage = "Python";



function findNewProgrammingLanguage(language) {


if (programminglanguages.indexOf(language) >=0) {


  console.log(language + "is present");


}


else {


  console.log(language + "is absent");


}


}



findNewProgrammingLanguage(newlanguage);

RegExp.test()

Em seguida, podemos usar o método RegExp.test() para encontrar uma substring. Esse método retorna um boolean e, portanto, é muito mais fácil de usar. Em comparação com o método indexOf(), ele retorna resultados diretos true ou false e pode ser uma boa alternativa.

var programminglanguages = "C++, JavaScript, Ruby";


var newlanguage = "Python";


function findNewProgrammingLanguage(language) {


var programmingReg = new RegExp(newlanguage);


if (programmingReg.test(programminglanguages)) {


  console.log(language + "is present");


}


else {


  console.log(language + "is absent");


}


}



findNewProgrammingLanguage(newlanguage);

Enquanto RegExp.test() é um ótimo método para usar, caracteres especiais podem ser um problema.

String.contains()

O último método é o String.contains(). Ele verifica diretamente se a substring está presente ou não e retorna um valor boolean. Este método está disponível a partir do ECMAScript 6 e, portanto, precisa ser usado com cautela.

Você tem alguma coisa a adicionar a este tutorial? Se sim, não se esqueça de comentar abaixo e deixe-nos saber.

Você também pode verificar em nosso site os vídeos sobre JavaScript. Abaixo estão alguns exemplos:

Full Stack Development in JavaScript

JavaScript Mobile Application

Dr. Michael J. Garbade

I, Dr. Michael J. Garbade is the co-founder of the Education Ecosystem (aka LiveEdu), ex-Amazon, GE, Rebate Networks, Y-combinator. Python, Django, and DevOps Engineer. Serial Entrepreneur. Experienced in raising venture funding. I speak English and German as mother tongues. I have a Masters in Business Administration and Physics, and a Ph.D. in Venture Capital Financing. Currently, I am the Project Lead on the community project -Nationalcoronalvirus Hotline I write subject matter expert technical and business articles in leading blogs like Opensource.com, Dzone.com, Cybrary, Businessinsider, Entrepreneur.com, TechinAsia, Coindesk, and Cointelegraph. I am a frequent speaker and panelist at tech and blockchain conferences around the globe. I serve as a start-up mentor at Axel Springer Accelerator, NY Edtech Accelerator, Seedstars, and Learnlaunch Accelerator. I love hackathons and often serve as a technical judge on hackathon panels.

Recent Posts

Highest Stable Coin Yields – (W16 – 2024)

Another week to bring you the top yield platforms for three of the most prominent…

2 weeks ago

LEDU Token OTC Trading

If you hold a large volume of LEDU tokens above 1 million units and wish…

1 month ago

Highest Stable Coin Yields – (W12 – 2024)

It’s another week and like always we have to explore the top yield platforms for…

1 month ago

Binance Auto Invest – the Best Innovation in Crypto since Sliced Bread

At a time where we’re constantly seeking tools and strategies to simplify our crypto investments,…

1 month ago

Highest Stable Coin Yields – March 2024

As we kick off another week, it's time to explore the top yield platforms for…

2 months ago

Education Ecosystem Featured on Business Insider

We're excited to share that Education Ecosystem was recently featured in an article on Business…

2 months ago