How to do strstr() in jquery

Asked

Viewed 3,211 times

2

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

I need to create a Function?

I want to be checked if there is the exact string that I am passing in another string, for example:

if(strstr("abc", "abcdefgh")){
...
}

4 answers

6


It is not necessary jQuery for this, only pure javascript, which already contains the function indexOf, 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');

Source


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

4

Use indexOf javascript that returns the position of a string in another. If the return of indexOf for -1 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. */
}

2

There’s a really cool project called php.js, there are Javascript implementations of the main functions of PHP, including the strstr(), it is possible to inform even the third parameter.

Example of use:

strstr('Kevin van Zonneveld', 'van'); // Retorna 'van Zonneveld'

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>

hug!

  • Note that in the case of search the expected argument is a regular expression, not a string. To find a common string within the other (such as the corresponding PHP function) indexOf is more indicated (because the argument for search is implicitly converted to a regex - meaning that special characters within the string are interpreted as such, not taken literally).

Browser other questions tagged

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