将特殊字符转换为普通字符

时间:2013-05-08 10:50:10

标签: javascript regex special-characters

我尝试使用javascript AJAX从XML文件加载城市名称,最后成功加载它们。

var region=Ahmadābād,Sūrat,Vadodara,Rājkot,Bhāvnagar,Jāmnagar,Nadiād,Gāndhīnagar,Jūnāgadh,Surendranagar

这是我的输出;在这个输出中,一些字符是非标准的US ASCII,我想改成普通的字符,例如:

var region:- Ahmadabad,Surat,Vadodara,Rajkot,Bhavnagar,Jamnagar,Nadiad,Gandhinagar,Junagadh,Surendranagar

我该怎么做?

1 个答案:

答案 0 :(得分:0)

这是一个纯粹的JavaScript解决方案,虽然它不是最佳的,可能表现不佳:

// create a character map to convert one char to another
var charMap = {
    "ā" : "a",
    "ū" : "u"
};
var region="Ahmadābād,Sūrat,Vadodara,Rājkot,Bhāvnagar,Jāmnagar,Nadiād,Gāndhīnagar,Jūnāgadh,Surendranagar";

// split original string into char array
var chars = region.split('');
// init new array for conversion result
var charsConverted = [];

// convert characters one by one
for(var i = 0; i < chars.length; i++){
    var char = chars[i];
    // this will try to use a matching char from char map
    // will use original if no pair found in charMap
    charsConverted.push( charMap[char] || char);
}

// join array to string
var result = charsConverted.join('');

alert(region);
alert(result);

这只是一个想法,可能需要进行大量调整。

行动准则:http://jsfiddle.net/L5Yzf/

HTH