index with regular expression using variable

Asked

Viewed 403 times

2

I use the index to check if a string contains a certain text. However, this is case sensitive and accents sensitive.

Would there be some way for example I find these records in case to enter in the search any of them following?:

  • Joao
  • Joao
  • Joao
  • john
  • John

I imagine with regular expression I could manage, but I don’t quite understand how they work yet. Especially when it comes to a variable.

My code is like this:

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

if(meuTexto.indexOf(textoBusca) != -1){
    alert("Foram encontrados registros");
}

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 issue indicated by mgibsonbr to remove the accentuation of both the search text and what will be searched.

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

Another alternative, without using Regex, would be to convert all text to letters capital letters or lowercase and use the indexOf even.

Finally, if the idea is to search only whole words in a text that is not very large, there is still the possibility to break the original text into words and compare one to one using the function localeCompare. This function has parameters that ignore accentuation and marry.

For example, consider the following commands:

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

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

Browser other questions tagged

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