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

11

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

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

    
asked by anonymous 30.01.2014 / 11:35

2 answers

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

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

    
30.01.2014 / 11:38
8

Using a regex it is possible to know if certain text is contained in another, using method match() . Your regex should be delimited by //

modifiers in js

list of metacharacters

var str = 'algum texto';
if(str.match(/texto/)){
  alert('string encontrada');
}
    
30.01.2014 / 11:39