[개발] 프로그램 지식

[html/js] – & 등과 같은 문자 출력되는 경우 대처법, 참고 코드

  • -
반응형

문제상황

일부 input, textarea에서 위와같은 식으로 문자가 출력되는 현상

 

 

해결방법

: 치환 함수만들어서, class에 지정해줌

 

 

 

참고코드

<input type="text" class="htmlEscapeVal" name="inputName">
<input type="text" class="htmlEscapeText" name="inputName">

 

// 특수 문자 치환 (html 모두 그려진 뒤 실행해야 함)
$(document).ready(function() {
	$('.htmlEscapeVal').each(function() {
		$(this).val(replaceSpecialCharacters($(this).val()));
	});
	
	$('.htmlEscapeText').each(function() {
		$(this).text(replaceSpecialCharacters($(this).text()));
	});
});

 

//특수 문자 치환  함수
function replaceSpecialCharacters(str) {
	if (str == null) {
	 return "";
	}
	
	return str
		.replace(/&amp;/g, '&')
		.replace(/amp;/g, '')
		.replace(/&ndash;/g, '-')
		.replace(/&lt;/g, '<')
		.replace(/&gt;/g, '>')
		.replace(/&quot;/g, '"')
		.replace(/&#039;/g, "'")
		.replace(/&#39;/g, "'")
		.replace(/&middot;/g, "·")
		.replace(/&sdot;/g, "⋅");
}

 

 

참고 사이트

https://html.spec.whatwg.org/multipage/named-characters.html

 

HTML Standard

HTMLLiving Standard — Last Updated 19 March 2024 ← 13.2 Parsing HTML documents — Table of Contents — 14 The XML syntax → 13.5 Named character references 13.5 Named character references This table lists the character reference names that are suppo

html.spec.whatwg.org

 

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.