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>

 

번호 제목 글쓴이 날짜 조회 수
110 현재 document 의 host 와 port 를 얻는 방법 황제낙엽 2023.10.03 1
109 (Bard) FileReader 로 여러개의 파일을 read 하는 법 file 황제낙엽 2023.08.23 0
108 navigator.mediaDevices 황제낙엽 2023.08.21 1
107 Barcode Detection API 황제낙엽 2023.08.06 6
106 체크박스에 체크된 항목 개수 구하기 황제낙엽 2023.06.10 1
105 배열에 대한 루프문 조회 (loop iterator) 황제낙엽 2023.03.01 3
104 (Copilot) 바닐라 스크립트가 뭐지? 황제낙엽 2023.02.24 7
103 문자열에서 역슬래시(backslash) 문자와 유니코드(Unicode)에 대한 고찰 file 황제낙엽 2021.06.03 160
102 자바스크립트(Javascript) escape, encodeURI, encodeURIComponent 인코딩 함수 황제낙엽 2021.04.27 34
101 자바스크립트 학습용 유튜브 강의 (드림코딩 by 엘리) 황제낙엽 2021.03.07 119
100 Early return, early exit - 스크립트 가독성 개선 팁 황제낙엽 2021.03.07 19
99 [GitHub] JavaScript Algorithms and Data Structures (알고리즘과 자료구조) file 황제낙엽 2021.03.01 11
98 비동기프로그래밍 - 콜백함수(Callback function) file 황제낙엽 2020.08.26 33
97 Strict 모드 황제낙엽 2020.08.23 10
96 서비스 워커 file 황제낙엽 2020.05.25 177
95 경과 시간 구하기 황제낙엽 2019.10.04 1071
94 입력받은 날짜와 현재 날짜와의 비교 함수 황제낙엽 2019.08.02 499
93 사용자 모듈 만들기 황제낙엽 2019.07.09 41735
» charcode 32와 160 차이 (javascript char 160 to 32) 황제낙엽 2019.05.11 55
91 부동소수점 (floating-point) file 황제낙엽 2018.03.26 1122