How to do strstr () in jquery

2

Is there any way to do strstr () (which exists in php) in jQuery?

Do I need to create a function?

I want to be checked for the exact string I'm passing in another string, for example:

if(strstr("abc", "abcdefgh")){
...
}
    
asked by anonymous 05.11.2014 / 14:40

4 answers

6

You do not need jQuery for this, just pure javascript, which already contains the indexOf function, example.

var str = "Hello world, welcome to the universe.";
var n = str.indexOf("welcome");

if (n > -1) alert('Termo encontrado');
else alert('Termo não encontrado');

Font

jQuery is a cross-browser JavaScript library designed to simplify client side scripts that interact with HTML. Wikipedia

    
05.11.2014 / 14:48
4

Use indexOf of javascript that returns the position of a string in another. If the return of indexOf is -1 it means that the first string is not within the second.

Example

if("string que contém".indexOf("string contida") < -1){
  /* O que fazer se não encontrar a string */ 
}
else{
  /* O que fazer se a string for encontrada. */
}
    
05.11.2014 / 14:46
2

Yes, you will need to create a function.

<script type="text/javascript">

     var chave = /vai/;
     var string = "Como vai Amancio";
     var resultado = string.search(chave);

     if(resultado != -1){
        alert("Encontrado: " + resultado); 
     }
     else{
        alert("Não foi possível encontrar");
     } 
</script>

Hugs!

    
05.11.2014 / 14:49
2

There is a very cool project called php.js , there are Javascript implementations of the main PHP functions, including strstr () , being able to inform even the third parameter.

Example usage:

strstr('Kevin van Zonneveld', 'van'); // Retorna 'van Zonneveld'
    
06.11.2014 / 15:27