2013-12-17 10 views
0

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".length2이 아닌 4이 아닌 이유를 이해할 수 없습니다.

도와주세요.
고마워요.

+1

"$ 2".length에 동적 일 수 있도록이

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

과 같이해야한다 대체하기 전에 평가됩니다. 그게 2 인 이유입니다. – bfavaretto

+0

아, 그게 이유입니다. thx – xpt

답변

1

당신은 "$2".convert() 할 수없고, 당신이 정규 표현식을 정의 할 때 "$2".length, 그것은 스크립트가 모든 일치하는 결과

+0

전체 기능을 제발 할 수 있을까요? 며칠 전에 자바 스크립트를 모르는 사람으로 구타하기가 여전히 어렵다. FTR, 나는 이것을 시도했다'String.prototype.decode = function (start, length) { return this.replace ( new RegExp ("{{+ start +"})) "), function (m1, m2) { return m2.length; }); }';하지만 반환 된 결과는 4 대신 5입니다. – xpt

관련 문제