indexOf with regular expression using variable [duplicate]

2

I use indexOf to check if a string contains a given text. But this is case sensitive and also sensitive to accents.

Would there be any way for me to find these records in the case of entering any of the following in the search:

  • joao
  • Joao
  • jOao
  • joão
  • John

I imagine that with regular expression I could achieve, but I do not understand very well how they work. Especially when it comes to a variable.

My code looks like this:

var textoBusca = $("#campoBusca").val();

if(meuTexto.indexOf(textoBusca) != -1){
    alert("Foram encontrados registros");
}
    
asked by anonymous 26.03.2015 / 20:47

1 answer

3

There are different ways to do this and it will depend on your goal.

First, to ignore the accents you can use the solutions of this question indicated by mgibsonbr to remove accentuation of both the search text and what will be searched.

Then you can choose to use search to perform a case-insensitive search using Regex.

Another alternative, without using Regex, would be to convert all text to letters uppercase or lowercase and use the % with% same.

Finally, if the idea is to search for whole words only in a text that is not too large, there is still the possibility of breaking the original text into words and comparing it one by one using the indexOf . This function has parameters that ignore accent and case .

For example, consider the following commands:

console.log('á'.localeCompare('a', 'br', { sensitivity: 'base' })); 
console.log('Ã'.localeCompare('a', 'br', { sensitivity: 'base' })); 

Both return localeCompare (zero) because they consider the letters equal.

    
26.03.2015 / 22:11