How can I check if one string contains another in Javascript?

Asked

Viewed 72,494 times

17

I would like to check if one string contains another, as if it were a method String.contains() but apparently there is no method to do this.

Does anyone know a similar method that does the same thing?

3 answers

36


Use the function indexOf:

var s = "foo";
alert(s.indexOf("oo") != -1);

The function indexOf returns the position of a string in another string or -1 if it does not find.

12

Using one regex it is possible to know if certain text is contained in another, using method match(). Its regex must be bounded by //

modifiers in js

metacharacter list

var str = 'algum texto';
if(str.match(/texto/)){
  alert('string encontrada');
}
  • What if I wanted to find more than one word in a sentence? Example: Some text here I want to know if there are the words "text" or "Here", is like?

5

It is also possible to find string inside another through the method includes():

let string = 'Meu texto aqui';
let result = string.includes('texto');

console.log(result);

This is very useful if used with the method filter() for example:

let string = 'Tamanho 12,12cm';
let array = string.split(' ');

let filtro = array.filter(valor => valor.includes(','))

console.log(filtro);    // em forma de array
console.log(String(filtro));   // em forma de string

Browser other questions tagged

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