0

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.

1
  • 1
    "$2".length is evaluated before the replace, that's why it's 2. Commented Dec 17, 2013 at 3:26

1 Answer 1

1

You can't do "$2".convert() and "$2".length when you define the regular expressions, it should be something like this

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

so that the script worked dynamically on every matching result

Sign up to request clarification or add additional context in comments.

1 Comment

Could you make it a full function please? It's still hard for me to grok as someone who doesn't know javascript several days ago, and still don't. FTR, I tried this String.prototype.decode = function(start, length) { return this.replace( new RegExp("^(.{" + start + "})(.{" + length + "})"), function(m1, m2) { return m2.length; }); }; but the returned result is 5 instead of 4.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.