用于转换UTF8子字符串的Javascript函数
接下来,这次我只想替换字符串的一部分 我想我已经找到了我想要的所有答案(来自上一篇文章和),但我不能把它们全部放在一起。请看下面的演示:用于转换UTF8子字符串的Javascript函数,javascript,string,utf-8,character,converter,Javascript,String,Utf 8,Character,Converter,接下来,这次我只想替换字符串的一部分 我想我已经找到了我想要的所有答案(来自上一篇文章和),但我不能把它们全部放在一起。请看下面的演示: // 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
// 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 ABCabc ABC!代码>)
在上一个测试中,有一个测试是“$2.length
,我不明白为什么“$2.length
是2
,而不是4
请帮帮我。
非常感谢。您不能执行“$2.convert()
和“$2.length”
定义正则表达式时,应该是这样的
return this.replace(new RegExp(...), function(m1, m2) {
return m2.length;
});
因此,脚本在每个匹配结果上都会动态运行“$2”。替换之前会计算长度,这就是为什么它是2。请将其设置为完整函数好吗?几天前,我还是很难像一个不懂javascript的人一样摸索,现在仍然不懂。FTR,我尝试了这个String.prototype.decode=function(start,length){返回这个.replace(新的RegExp(“^(.{start+”})(.{length+”})”),function(m1,m2){return m2.length;})代码>但返回的结果是5而不是4。