JavaScript function to convert UTF8 string between fullwidth and halfwidth forms을 추적하면서 이번에는 문자열의 일부만 바꾸길 원합니다.UTF8 하위 문자열을 변환하는 JavaScript 함수
내가 이전에 게시 한 답변 (이전 게시물 및 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!"
즉, 내 모든 문자열을 연장하는 방법이 (자바 스크립트 몇 일 전 모르는 사람의 눈에) 제대로 정의되어 있다고 생각합니다. 그러나 그들을 합칠 때 그들은 기대했던대로 작동하지 않습니다().
마지막 테스트 인 "$2".length
으로 테스트 한 결과 "$2".length
은 2
이 아닌 4
이 아닌 이유를 이해할 수 없습니다.
도와주세요.
고마워요.
"$ 2".length에 동적 일 수 있도록이
과 같이해야한다 대체하기 전에 평가됩니다. 그게 2 인 이유입니다. – bfavaretto
아, 그게 이유입니다. thx – xpt