sitelink1 https://blog.naver.com/bb_/221449936369 
sitelink2  
sitelink3  
sitelink4  
extra_vars4  
extra_vars5  
extra_vars6  

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>

 

번호 제목 글쓴이 날짜 조회 수
206 [GitHub] JavaScript Algorithms and Data Structures (알고리즘과 자료구조) file 황제낙엽 2021.03.01 595
205 콜백지옥과 비동기제어 file 황제낙엽 2021.02.18 1590
204 Json 특징 및 문법 황제낙엽 2021.01.26 522
203 비동기프로그래밍 - 콜백함수(Callback function) file 황제낙엽 2020.08.26 681
202 Strict 모드 황제낙엽 2020.08.23 627
201 window.postMessage() 황제낙엽 2020.07.29 2114
200 withCredentials 관련 황제낙엽 2020.07.29 542
199 CORS 관련 레퍼런스 URL 황제낙엽 2020.07.10 590
198 ECMA 스크립트의 JSON 황제낙엽 2019.10.16 580
197 경과 시간 구하기 황제낙엽 2019.10.04 1673
196 입력받은 날짜와 현재 날짜와의 비교 함수 황제낙엽 2019.08.02 1049
195 사용자 모듈 만들기 황제낙엽 2019.07.09 42275
» charcode 32와 160 차이 (javascript char 160 to 32) 황제낙엽 2019.05.11 580
193 UTF-8 한글 초성 추출 (자바스크립트) 황제낙엽 2019.05.07 750
192 IE브라우저에서 서버의 XML파일을 ajax로 가져와 DOM파싱하는 예제 (XMLHttpRequest, XML, ActiveXObject) 황제낙엽 2018.11.23 652
191 XMLHttpRequest.timeout 황제낙엽 2018.11.03 779
190 부동소수점 (floating-point) file 황제낙엽 2018.03.26 1626
189 User Agent Parser들 황제낙엽 2017.11.20 6204
188 window.postMessage 이해하기 file 황제낙엽 2017.10.16 1904
187 브라우저의 새로고침과 종료에 대한 이벤트 황제낙엽 2017.08.11 3327