자바 스크립트에서 HTML 특수 문자를 이스케이프 처리 할 수 있습니까?
자바 스크립트 함수로 텍스트를 HTML로 표시하고 싶습니다. JS에서 HTML 특수 문자를 어떻게 피할 수 있습니까? API가 있습니까?
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
jQuery의 .text()
함수를 사용할 수 있습니다 .
예를 들면 다음과 같습니다.
.text()
함수 에 관한 jQuery 문서에서 :
이 메소드는 HTML에서 올바르게 렌더링되도록 필요에 따라 제공된 문자열을 이스케이프해야합니다. 이를 위해 DOM 메소드 .createTextNode ()를 호출하고 문자열을 HTML로 해석하지 않습니다.
이전 버전의 jQuery 문서는 다음과 같이 표현했습니다 ( 중점 추가 ).
이 메소드는 HTML에서 올바르게 렌더링되도록 필요에 따라 제공된 문자열을 이스케이프해야합니다. 이를 위해 DOM 메소드 .createTextNode ()를 호출하여 특수 문자를 해당 HTML 엔티티 (예 : & amplt; for <)로 바꿉니다.
function escapeHtml(html){
var text = document.createTextNode(html);
var p = document.createElement('p');
p.appendChild(text);
return p.innerHTML;
}
// Escape while typing & print result
document.querySelector('input').addEventListener('input', e => {
console.clear();
console.log( escapeHtml(e.target.value) );
});
<input style='width:90%; padding:6px;' placeholder='<b>cool</b>'>
적절한 방법을 찾았다 고 생각합니다 ...
// Create a DOM Text node:
var text_node = document.createTextNode(unescaped_text);
// Get the HTML element where you want to insert the text into:
var elem = document.getElementById('msg_span');
// Optional: clear its old contents
//elem.innerHTML = '';
// Append the text node into it:
elem.appendChild(text_node);
lodash 사용
_.escape('fred, barney, & pebbles');
// => 'fred, barney, & pebbles'
이것은 지금까지 내가 본 가장 빠른 방법입니다. 또한 페이지의 요소를 추가, 제거 또는 변경하지 않고 모든 작업을 수행합니다.
function escapeHTML(unsafeText) {
let div = document.createElement('div');
div.innerText = unsafeText;
return div.innerHTML;
}
더 나은 솔루션을 찾는 것이 흥미로 웠습니다.
var escapeHTML = function(unsafe) {
return unsafe.replace(/[&<"']/g, function(m) {
switch (m) {
case '&':
return '&';
case '<':
return '<';
case '"':
return '"';
default:
return ''';
}
});
};
>
결과에서 XML / HTML 코드를 손상시키지 않기 때문에 구문 분석 하지 않습니다.
벤치 마크는 다음과 같습니다. http://jsperf.com/regexpairs 또한 범용 escape
기능을 만들었습니다 . http://jsperf.com/regexpairs2
The most concise and performant way to display unencoded text is to use textContent
property.
Faster than using innerHTML
. And that's without taking into account escaping overhead.
document.body.textContent = 'a <b> c </b>';
DOM Elements support converting text to HTML by assigning to innerText. innerText is not a function but assigning to it works as if the text were escaped.
document.querySelectorAll('#id')[0].innerText = 'unsafe " String >><>';
You can encode every character in your string:
function encode(e){return e.replace(/[^]/g,function(e){return"&#"+e.charCodeAt(0)+";"})}
Or just target the main characters to worry about (&, inebreaks, <, >, " and ') like:
function encode(r){
return r.replace(/[\x26\x0A\<>'"]/g,function(r){return"&#"+r.charCodeAt(0)+";"})
}
test.value=encode('How to encode\nonly html tags &<>\'" nice & fast!');
/*************
* \x26 is &ersand (it has to be first),
* \x0A is newline,
*************/
<textarea id=test rows="9" cols="55">www.WHAK.com</textarea>
Came across this issue when building a DOM structure. This question helped me solve it. I wanted to use a double chevron as a path separator, but appending a new text node directly resulted in the escaped character code showing, rather than the character itself:
var _div = document.createElement('div');
var _separator = document.createTextNode('»');
//_div.appendChild(_separator); /* this resulted in '»' being displayed */
_div.innerHTML = _separator.textContent; /* this was key */
Try this, using the prototype.js
library:
string.escapeHTML();
I came up with this solution.
Let's assume that we want to add some html to the element with unsafe data from the user or database.
var unsafe = 'some unsafe data like <script>alert("oops");</script> here';
var html = '';
html += '<div>';
html += '<p>' + unsafe + '</p>';
html += '</div>';
element.html(html);
It's unsafe against XSS attacks. Now add this.
$(document.createElement('div')).html(unsafe).text();
So it is
var unsafe = 'some unsafe data like <script>alert("oops");</script> here';
var html = '';
html += '<div>';
html += '<p>' + $(document.createElement('div')).html(unsafe).text(); + '</p>';
html += '</div>';
element.html(html);
To me this is much easier than using .replace()
and it'll remove!!! all possible html tags (I hope).
참고URL : https://stackoverflow.com/questions/6234773/can-i-escape-html-special-chars-in-javascript
'Programming' 카테고리의 다른 글
jQuery를 사용하여 페이지의 스크롤 위치를 감지하는 방법 (0) | 2020.06.01 |
---|---|
위도 / 경도는 가장 가까운 위도 / 경도를 찾습니다-복잡한 SQL 또는 복잡한 계산 (0) | 2020.06.01 |
Intellij-최신 Java 8 클래스를 사용할 수 없음-오류 :“@since 1.6 이상으로 문서화 된 API 사용 ..” (0) | 2020.06.01 |
SQL Server 로그인이 이미 있는지 확인 (0) | 2020.06.01 |
UITableView가 ReloadData를 완료 한 시점을 알리는 방법? (0) | 2020.06.01 |