简体   繁体   English

如何在忽略特殊字符的javascript中比较字符串

[英]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.我已经用toUpperCase()管理了大写,但我仍然想确保我没有重音问题。

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? PD:我会借此机会问:使用口音的正确编码是什么? UTF-8? UTF-8?

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM