2013-12-17 133 views
0

跟進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".length2但不4

請幫我一把。
非常感謝。

+1

「$ 2」。長度在更換前評估,這就是爲什麼它是2. – bfavaretto

+0

啊,這就是爲什麼。 thx – xpt

回答

1

你不能這樣做"$2".convert()"$2".length當您定義的正則表達式,它應該是這樣的

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

這樣腳本動態的工作在每一個匹配結果

+0

請問您可以讓它成爲一個完整的功能嗎?對於我幾天前還不知道JavaScript的人來說,仍然很難,但仍然不會。 FTR,我試過這個'String.prototype.decode = function(start,length)return this.replace( new RegExp(「^(。{」+ start +「})(。{」+ length +「} )「),函數(m1,m2){ return m2.length; }); };'但返回的結果是5而不是4。 – xpt