Following up with JavaScript function to convert UTF8 string between fullwidth and halfwidth forms, this time I want to replace only part of the string.
I think I have found all the answers that I want (from previous post and Replace substring in string with range in JavaScript), but I just can't put it all together. Please take a look at the following demonstration:
// 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!"
I.e., I believe that all my string extending methods are defined properly (in the eyes of someone who doesn't know javascript several days ago). But when putting them together, they don't work as I expected (!abc ABC!!abc ABC!).
Further the last test, the one test with "$2".length, I just can't understand why "$2".length is 2 but not 4.
Please help me out.
Thanks a lot.