Search code examples
javascriptunicodestring-comparison

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?


Solution

  • 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 ));
    });