跟進JavaScript function to convert UTF8 string between fullwidth and halfwidth forms,這次我只想替換部分字符串。使用Javascript函數轉換UTF8子串
我想我已經找到了我想要的所有答案(來自以前的帖子和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".length
是2
但不4
。
請幫我一把。
非常感謝。
「$ 2」。長度在更換前評估,這就是爲什麼它是2. – bfavaretto
啊,這就是爲什麼。 thx – xpt