Javascript函数转换UTF8子字符串

时间:2013-12-17 03:23:15

标签: javascript string utf-8 character converter

跟进JavaScript function to convert UTF8 string between fullwidth and halfwidth forms,这次我只想替换部分字符串。

我想我已经找到了我想要的所有答案(来自之前的帖子和Replace substring in string with range in JavaScript),但我不能把它们全部放在一起。请看下面的演示:

// Extend the string object to add a new method convert
String.prototype.convert = function() {
return this.replace(    /[\uff01-\uff5e]/g,
function(ch) { return String.fromCharCode(ch.charCodeAt(0) - 0xfee0); }
)
};

// Test and verify it's working well:
> instr = "!abc ABC!!abc ABC!"
"!abc ABC!!abc ABC!"

> instr.substr(5, 4)
"ABC!"

> instr.substr(5, 4).convert()
"ABC!"
// Great!

// Goal: define a decode method like this 
String.prototype.decode = function(start, length) {
return this.replace(
new RegExp("^(.{" + start + "})(.{" + length + "})"), "$1" + "$2".convert());
};

// Test/verify failed:
> instr.decode(5, 4)
"!abc ABC!!abc ABC!"

// That failed, now define a test method to verify
String.prototype.decode = function(start, length) {
return this.replace(
new RegExp("^(.{" + start + "})(.{" + length + "})"), "$2".length);
};

> instr.decode(5, 4)
"2!abc ABC!"

即,我相信我的所有字符串扩展方法都已正确定义(在几天前不知道javascript的人眼中)。但是当把它们组合在一起时,它们并不像我预期的那样工作(!abc ABC!!abc ABC!)。

进一步的最后一次测试,"$2".length的一次测试,我只是无法理解为什么"$2".length2而不是4

请帮帮我 非常感谢。

1 个答案:

答案 0 :(得分:1)

在定义正则表达式时,您无法执行"$2".convert()"$2".length,它应该是这样的

return this.replace(new RegExp(...), function(m1, m2) {
  return m2.length;
});

以便脚本在每个匹配结果上动态工作

相关问题