Get piece of text inside a javascript word

Asked

Viewed 1,019 times

12

I need to check if there is a specific piece within an excerpt of a javascript word.

For example, my word is John, I need to check if Jo contains inside her.

I tried to do it with the index but it didn’t work with the match but it didn’t 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?

  • What’s inside url?

  • ops, is id instead of url

  • 1

    Good, but what exactly appears in id? It seems pretty simple what you want to do, the index, the match or even a Regex should work. Maybe it’s another problem...

  • Appears something like "txtOutrosNomes2", "txtOther"

5 answers

5


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

var w = "João";
var r = /Jo/i;
r.test(w) //retorna true...

3

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

let url = "João";

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

It is important to check if the comparisons will be correct, maybe you may wish to disregard sensitive cases (cases sensitives), accentuation and/or spaces.

3

I suggest converting both the string you want to search for and the text where the search will be done in lowercase, thus avoiding that the string is not found because Javascript is case insentivive. So 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 "João".

1

You can use the IndexOf()

When it returns -1 the string was not found

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

if( text.indexOf( term ) != -1 )
    alert(term);

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 take a read on regular expressions (regex). With her her string treatments got much better. In the example I gave above I didn’t use regex to suit what you were doing earlier.

Browser other questions tagged

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