Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare strings in javascript ignoring special characters

I'm developing an app and I've been asked to compare strings, but text in string have special characters (spanish accents like "á", "é", "í", "ó" and "ú")

I already manage capitalization with toUpperCase(), but still, I want to be sure that I have no problem with accents.

What I have to do is to compare some words already saved in system and check if used typed any of them.

What I do is store the typed words in an array, and then proceed to analyze them in another function (yet to be implemented)

This is my function where I store the words the user types (it may change to make it more complete):

function clickNewWord(){
    var theWord = textField.value.toUpperCase();
    ArrayWrittenWords.push(theWord);
    textField.value = "";
}

PD: I'll take the opportunity to ask: What would be the correct coding to work with accents? UTF-8?

like image 289
Sascuash Avatar asked Nov 15 '25 17:11

Sascuash


2 Answers

Although its an old question however, for the sake of future googlers here is the best way to remove accent from a string:

var string = 'á é í ó ú';
string.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
>a e i o u
like image 186
Ekeuwei Avatar answered Nov 18 '25 07:11

Ekeuwei


You can convert them and then match them, let me if my example is clear :)

var stringInTheSystem = ['aaaa','bbbb'];// Array of string in your system;

var term = 'áaaa';// the word you want to compare it; 
term = term.replace(/á/g, "a"); 
term = term.replace(/é/g, "e"); 
term = term.replace(/í/g, "i"); 
term = term.replace(/ó/g, "o"); 
term = term.replace(/ú/g, "u"); 
var matcher = new RegExp( term, "i" );
$.grep( stringInTheSystem, function( value ) {
                  value = value.test || value.value || value;
                    console.log(matcher.test( value ));
});
like image 44
Mouhamad Kawas Avatar answered Nov 18 '25 06:11

Mouhamad Kawas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!