[자바스크립트] charcode 32와 160 차이 (javascript char 160 to 32)
charcode 32는 공백(Space)이고, 160은 NBSP(non-breaking space) 이다.
두 가지 모두 공백이지만, 같은 소스코드의 페이지라도 브라우저에 따라 컴포넌트 내의 문자열을 서로 다르게 가져온다. (ex: textarea 에서 문자열을 가져올 때)
익스플로러는 32로만 가져오는데, 크롬은 32와 160을 섞어서 가져오는 경우가 많은듯 하다.
따라서 두 가지 공백을 하나로 통일해주는 코드가 필요하다.
구글링 결과 크게 다음 3가지 코드가 있다.
(1) 32와 160을 모두 공백(32)으로 변경
return _text.replace(/\s+/g, ” “);
(2) 160만 공백(32)으로 변경
return _text.replace(new RegExp(String.fromCharCode(160),”g”), ” “);
(3) 160만 공백(32)으로 변경
return _text.replace(/\xA0/g, ” “);
다음은 직접 작성한 예제소스.
로컬에 html 파일로 저장해서 실행하면 된다.
|
<html> <head> <script> window.onload = function() { doTest(); }
function doTest() { alert(“doTest”); var beforeText = “대” + String.fromCharCode(32) + “학” + String.fromCharCode(160) + “교”; var afterText = replaceNbsp(beforeText); alert(“BEFORE : ” + getCharCodeFromText(beforeText)); alert(“AFTER : ” + getCharCodeFromText(afterText)); }
// 문자열을 캐릭터코드로 변경해서 리턴 function getCharCodeFromText(_text) { if (_text == null || _text == “”) { return “empty”; }
var result = “”; var len = _text.length; for (var i=0; i<len; i++) { if (result.length > 0) { result += “/”; } result += _text.charCodeAt(i); } return result; }
function replaceNbsp(_text) { if (_text == null || _text == “”) { return “”; }
// (1) 32와 160을 모두 공백(32)으로 변경 // return _text.replace(/\s+/g, ” “); // (2) 160만 공백(32)으로 변경 return _text.replace(new RegExp(String.fromCharCode(160),”g”), ” “); // (3) 160만 공백(32)으로 변경 // return _text.replace(/\xA0/g, ” “); } </script> </head> <body> </body> </html>
|