用js中数组中的其他字符替换特殊字符

replacing special characters with other character from array in js

本文关键字:字符 替换 其他 特殊字符 js 数组      更新时间:2023-09-26

我想通过比较它的每个字符与数组中的字符并将其替换为匹配的字符来摆脱字符串中的特殊字符。下面的函数不会抛出任何错误,但会继续返回字符串

    var name = "przykład";      
    // the characters i'm looking for in a string:
    var charList = ["Ą","ą","Ć","ć","Ę","ę","Ł","ł","Ó","ó","Ś","ś","Ź","ź","Ż","ź"];
    // the characters i'd like to replace them with:
    var replaceList = ["A","a","C","c","E","e","L","l","O","o","S","s","Z","z","Z","z"];
    var limit = name.length;
    for (i = 0; i < limit; i++){
        for(var j in charList){
            name.charAt(i) === charList[j] ? name.replace(name.charAt(i), replaceList[j]) : "";
        }
    }
    return name;

我知道这个问题很可能会以"太本地化"结束,这可能是我犯的一个愚蠢而容易的错误,但我仍然非常感谢任何帮助

在大多数编程语言中,replace函数的结果通常作为一个新的String对象返回。你应该这样修改你的代码:

if (name.charAt(i) === charList[j])
    name = name.replace(name.charAt(i), replaceList[j]);
此外,由于replace函数将替换中出现的所有字符,因此您可以稍微更改一下算法。

您可以将映射放入对象中,这样做的优点是更容易维护,因为字符及其替换在对象中是相邻的,而不是尝试在数组中对齐位置。

var name = "przykłąd Ęś";
// Object of characters to replace and their replacement values
var charList = {'Ą':'A', 'ą':'a', 'Ć':'C', 'ć':'c', 'Ę':'E', 'ę':'e',
                'Ł':'L', 'ł':'l', 'Ó':'O', 'ó':'o', 'Ś':'S', 'ś':'s',
                'Ź':'Z', 'ź':'z', 'Ż':'Z', 'ż':'z'};
// For each character in the string, search for it in charList and if found,
// replace it with the value
alert(
  name + ''n' + name.replace(/./g, function(c) {return c in charList? charList[c] : c})
);

很可能有一些更聪明的方法可以用char代码来完成,但是我现在想不出来。

2017年

编辑

固定最后一个字符映射-谢谢@MarekSkiba。: -)

这是我的解决方案…

var cleanName = function(str) {
    if ($.trim(str) == '') return str; // jQuery
    str = $.trim(str).toLowerCase();
    var special = ['&', 'O', 'Z', '-', 'o', 'z', 'Y', 'À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ð', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ', '.', ' ', '+', ''''],
        normal = ['et', 'o', 'z', '-', 'o', 'z', 'y', 'a', 'a', 'a', 'a', 'a', 'a', 'ae', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'd', 'n', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'a', 'a', 'a', 'a', 'a', 'a', 'ae', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'o', 'n', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'y', '_', '_', '-', '-'];
    for (var i = 0; i < str.length; i++) {
        for (var j = 0; j < special.length; j++) {
            if (str[i] == special[j]) {
                str = str.replace(new RegExp(str[i], 'gi'), normal[j]);
            }
        }
    }
    str = str.replace(/[^a-z0-9_'-]/gi, '_');
    str = str.replace(/['-]{2,}/gi, '_');
    str = str.replace(/['_]{2,}/gi, '_');
    return str;
};
console.log(cleanName('l''éléphant')); // "l-elephant"