Catching piece of text inside a javascript word

11

I need to check if there is a specific piece within a snippet of a word in javascript.

Example, my word is John, I need to check if Jo contains it.

I tried to do with indexOf but it did not work, but it did not work.

//pesquiso tudo que tem dentro dessa classe
$(".form-group").find('*').each(function() {
    var cont = 0;
    //pego todos os ids 
    var id = $(this).attr("id");
    //verifico se o trecho especifico contem o que eu preciso
    if (id.match("txtOutrosNomes") != -1) {
        console.log(cont++);
    }
});

How to make this comparison?

    
asked by anonymous 14.12.2017 / 12:53

5 answers

5

Hello I think you can do with Regex, for example:

var w = "João";
var r = /Jo/i;
r.test(w) //retorna true...
    
14.12.2017 / 12:59
3

match will return the combined text, so you could change your code in this way that will check if it is other than null:

let url = "João";

if (url.match("Jo")) {
  console.log("Match");
}

It's important to check if the comparisons will be correct, you might want to disregard sensitive cases, accentuation, and / or spaces.

    
14.12.2017 / 13:00
3

I suggest you convert the string you want to search and the text where the search will be made in tiny, so will prevent the string is not found by the fact that JavaScript be case insentivive . Then you can use indexOf :

$(".form-group").find('*').each(function() {
    var cont = 0;
    //pego todos os ids 
    var id = $(this).attr("id");
    //verifico se o trecho especifico contem o que eu preciso
    if (id.toLowerCase().indexOf("txtOutrosNomes".toLowerCase()) != -1) {
        console.log(cont++);
    }
});

In this case, you will find both "Jo" and "jo" in "John".

    
14.12.2017 / 13:03
1

You can use IndexOf()

When it returns -1 the string was not found

var text = this.variable;
var term = "jo";

if( text.indexOf( term ) != -1 )
    alert(term);
    
14.12.2017 / 12:58
0

You can use the match () function. < read more >

function contem(frase, palavra){
  if(frase != null && palavra != null){
    if(frase.match(palavra))
      return 'contem';
  }
  return 'não contem';
}


var txtContem = document.getElementById('contem');
txtContem.value = contem('João comeu pão', 'Jo');
<input type="text" id="contem" placeholder="contém ou não">

Also read regular expressions (regex). With it, your string treatments look better. In the example I gave above I did not use regex to fit with what you were doing previously.

    
14.12.2017 / 13:19