qod*_*nja 35 javascript perl transliteration character-encoding
我一直试图弄清楚如何将字符串中的一组字符映射到另一个类似于trPerl中的函数的集合.
我发现这个站点显示了JS和Perl中的等效函数,但遗憾的是没有tr等价.
trPerl中的(音译)函数将字符一对一映射,所以
data =~ tr|\-_|+/|;
Run Code Online (Sandbox Code Playgroud)
会映射
- => + and _ => /
Run Code Online (Sandbox Code Playgroud)
如何在JavaScript中有效地完成这项工作?
Jon*_*ski 53
没有内置的等价物,但你可以接近一个replace:
data = data.replace(/[\-_]/g, function (m) {
return {
'-': '+',
'_': '/'
}[m];
});
Run Code Online (Sandbox Code Playgroud)
小智 6
我不能保证"有效",但这使用正则表达式和回调来提供替换字符.
function tr( text, search, replace ) {
// Make the search string a regex.
var regex = RegExp( '[' + search + ']', 'g' );
var t = text.replace( regex,
function( chr ) {
// Get the position of the found character in the search string.
var ind = search.indexOf( chr );
// Get the corresponding character from the replace string.
var r = replace.charAt( ind );
return r;
} );
return t;
}
Run Code Online (Sandbox Code Playgroud)
对于长字符串的搜索和替换字符,可能值得将它们放在哈希中并使函数从中返回.即,tr/abcd/QRST /成为散列{a:Q,b:R,c:S,d:T},并且回调返回散列[chr].
方法:
String.prototype.mapReplace = function(map) {
var regex = [];
for(var key in map)
regex.push(key.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"));
return this.replace(new RegExp(regex.join('|'),"g"),function(word){
return map[word];
});
};
Run Code Online (Sandbox Code Playgroud)
一个完美的例子:
var s = "I think Peak rocks!"
s.mapReplace({"I think":"Actually","rocks":"sucks"})
// console: "Actually Peak sucks!"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17086 次 |
| 最近记录: |