입력 필드에서 속성을 읽을 때 HTML 인코딩이 손실됨
숨겨진 필드에서 값을 추출하여 텍스트 상자에 표시하기 위해 JavaScript를 사용하고 있습니다.숨김 필드의 값은 인코딩됩니다.
예를들면,
<input id='hiddenId' type='hidden' value='chalk & cheese' />
에 말려들다
<input type='text' value='chalk & cheese' />
일부 jQuery를 통해 숨겨진 필드의 값을 가져옵니다(이 시점에서 인코딩이 손실됩니다).
$('#hiddenId').attr('value')
는 때chalk & cheese
자바스크립트이 나나 i i i i i i i i i i i i 가 되지 않았으면 합니다.chalk & cheese
.amp;
유지가 됩니다.
문자열을 HTML 인코딩하는 JavaScript 라이브러리 또는 jQuery 메서드가 있습니까?
편집: 이 답변은 오래 전에 게시되었습니다.htmlDecode
XSS를 사용하다가 변경되어 요소가 되어 있습니다.div
a까지textarea
XSS의 기회를 줄입니다.그러나 요즘은 다른 anwwer에서 제안하는 바와 같이 DOMParser API를 사용하는 것이 좋습니다.
다음 기능을 사용합니다.
function htmlEncode(value){
// Create a in-memory element, set its inner text (which is automatically encoded)
// Then grab the encoded contents back out. The element never exists on the DOM.
return $('<textarea/>').text(value).html();
}
function htmlDecode(value){
return $('<textarea/>').html(value).text();
}
기본적으로 텍스트 영역 요소는 메모리에 작성되지만 문서에 추가되지는 않습니다.
에에 。htmlEncode
。innerText
「부호화」를 합니다.innerHTML
htmlDecode
。innerHTML
및 ''의 값"innerText
득됩니니다다
여기서 실행 예를 확인해 주세요.
jQuery 트릭은 따옴표를 인코딩하지 않으며 IE에서는 공백을 제거합니다.
이미 많이 사용/테스트된 장고 탈출 템플릿에 기초하여 필요한 기능을 만들었습니다.
이것은 공백 스트라이핑 문제에 대한 어떤 회피책보다도 간단하며(아마도 빠를 수 있습니다), 예를 들어 속성 값 내에서 결과를 사용하는 경우 필수인 따옴표를 인코딩합니다.
function htmlEscape(str) {
return str
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>');
}
// I needed the opposite function today, so adding here too:
function htmlUnescape(str){
return str
.replace(/"/g, '"')
.replace(/'/g, "'")
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/&/g, '&');
}
2013-06-17:
할 수 있는 , 이 을 알 수 있었습니다.replaceAll
★★★★
http://dumpsite.com/forum/index.php?topic=4.msg29#msg29http.com/forum/index.php?topic=4.msg29#msg29
(여기에서도 참조: 문자열 내의 모든 문자의 인스턴스를 바꾸는 가장 빠른 메서드)
퍼포먼스 결과는 다음과 같습니다.
http://jsperf.com/htmlencoderegex/25httpjsperf.com//25
는 내장된 한 결과를 합니다.replace
왜 더 빠른지 누가 설명해줬으면 좋겠어!?
2015-03-04:
Angular 금금 jsJS 에서는와 같은 을 사용하고 것을 알게 .JS에 관한 것입니다.
https://github.com/angular/angular.js/blob/v1.3.14/src/ngSanitize/sanitize.js#L435httpsgithub.com/angular/angular.js/blob/v1.3.14/src//sanitize.js#L435
또한 영숫자가 아닌 모든 문자를 엔티티로 변환할 뿐만 아니라 불분명한 유니코드 문제를 처리하고 있는 것으로 보입니다.문서에 UTF8 문자 집합이 지정되어 있는 한 후자는 필요하지 않다고 생각했습니다.
지난 도) 는 이 두 가지 중 에 얼마나 한지 잘
https://github.com/django/django/blob/1.8b1/django/utils/html.py#L44httpsgithub.com/django/django/blob/1.8b1//utils/html.py#L44
2016-04-06 데 :
으로 슬래시하는 것을 도 있습니다./
올바른 HTML 인코딩에는 필요하지 않지만 OWASP에서는 XSS 방지 대책으로 권장하고 있습니다.(댓글에 제안해 주신 @JNF님 감사합니다)
.replace(/\//g, '/');
두 jQuery보다 입니다..html()
및 「」를 참조해 주세요..replace()
처럼 따옴표가이렇게 하면 모든 공백이 유지되지만 jQuery 버전과 마찬가지로 따옴표는 처리되지 않습니다.
function htmlEncode( html ) {
return document.createElement( 'a' ).appendChild(
document.createTextNode( html ) ).parentNode.innerHTML;
};
속도: http://jsperf.com/htmlencoderegex/17
출력:
스크립트:
function htmlEncode( html ) {
return document.createElement( 'a' ).appendChild(
document.createTextNode( html ) ).parentNode.innerHTML;
};
function htmlDecode( html ) {
var a = document.createElement( 'a' ); a.innerHTML = html;
return a.textContent;
};
document.getElementById( 'text' ).value = htmlEncode( document.getElementById( 'hidden' ).value );
//sanity check
var html = '<div> & hello</div>';
document.getElementById( 'same' ).textContent =
'html === htmlDecode( htmlEncode( html ) ): '
+ ( html === htmlDecode( htmlEncode( html ) ) );
HTML:
<input id="hidden" type="hidden" value="chalk & cheese" />
<input id="text" value="" />
<div id="same"></div>
오래된 답변인 것은 알지만 행을 삭제하지 않고 IE에서 사용할 수 있는 답변의 변형을 게시하고 싶었습니다.
function multiLineHtmlEncode(value) {
var lines = value.split(/\r\n|\r|\n/);
for (var i = 0; i < lines.length; i++) {
lines[i] = htmlEncode(lines[i]);
}
return lines.join('\r\n');
}
function htmlEncode(value) {
return $('<div/>').text(value).html();
}
밑줄은 이를 위한 방법을 제공합니다.
> _.unescape( "chalk & cheese" );
"chalk & cheese"
> _.escape( "chalk & cheese" );
"chalk & cheese"
to다 note 。인코딩할 이 호호 the the인 경우 해 주십시오.undefined
★★★★★★★★★★★★★★★★★」null
1.같은 할 수 .jQuery 1.4.2 는 。
jQuery("<div/>").text(value).html is not a function
또는
Uncaught TypeError: Object has no method 'html'
해결책은 함수를 수정하여 실제 값을 확인하는 것입니다.
function htmlEncode(value){
if (value) {
return jQuery('<div/>').text(value).html();
} else {
return '';
}
}
플레인 Javascript를 원하시는 분들을 위해 제가 성공적으로 사용한 방법은 다음과 같습니다.
function escapeHTML (str)
{
var div = document.createElement('div');
var text = document.createTextNode(str);
div.appendChild(text);
return div.innerHTML;
}
FWIW, 부호화는 없어지지 않습니다.인코딩은 페이지 로드 중에 마크업 파서(브라우저)에 의해 사용됩니다.소스를 읽고 해석하고 브라우저에 DOM이 메모리에 로드되면 인코딩은 그것이 나타내는 것으로 해석됩니다.따라서 JS가 메모리 내의 모든 것을 읽기 위해 실행될 때 JS가 얻는 문자는 인코딩이 나타내는 문자입니다.
여기서는 엄밀하게 의미론만을 다루고 있을지도 모르지만 부호화의 목적을 이해해 주셨으면 합니다."잃어버렸다"는 말은 뭔가가 제대로 작동하지 않는 것처럼 들리게 한다.
Jquery 없이 더 빨라집니다.문자열 내의 모든 문자를 부호화할 수 있습니다.
function encode(e){return e.replace(/[^]/g,function(e){return"&#"+e.charCodeAt(0)+";"})}
또는 다음과 같이 (&, unebreaks, <, >, " 및 ') 걱정해야 할 주요 캐릭터만을 대상으로 합니다.
function encode(r){
return r.replace(/[\x26\x0A\<>'"]/g,function(r){return"&#"+r.charCodeAt(0)+";"})
}
test.value=encode('Encode HTML entities!\n\n"Safe" escape <script id=\'\'> & useful in <pre> tags!');
testing.innerHTML=test.value;
/*************
* \x26 is &ersand (it has to be first),
* \x0A is newline,
*************/
<textarea id=test rows="9" cols="55"></textarea>
<div id="testing">www.WHAK.com</div>
프로토타입에는 String 클래스에 내장되어 있습니다.프로토타입을 사용하거나 사용할 계획이라면 다음과 같은 작업을 수행할 수 있습니다.
'<div class="article">This is an article</div>'.escapeHTML();
// -> "<div class="article">This is an article</div>"
여기 간단한 Javascript 솔루션이 있습니다.매개 변수가 없는 개체 또는 매개 변수와 함께 사용할 수 있는 메서드 "HTMLEncode"를 사용하여 String 개체를 확장합니다.
String.prototype.HTMLEncode = function(str) {
var result = "";
var str = (arguments.length===1) ? str : this;
for(var i=0; i<str.length; i++) {
var chrcode = str.charCodeAt(i);
result+=(chrcode>128) ? "&#"+chrcode+";" : str.substr(i,1)
}
return result;
}
// TEST
console.log("stetaewteaw æø".HTMLEncode());
console.log("stetaewteaw æø".HTMLEncode("æåøåæå"))
나는 요지를 만들었다.htMLEncode 메서드 for javascript"를 참조하십시오.
// ref: https://github.com/angular/angular.js/blob/v1.3.14/src/ngSanitize/sanitize.js
const SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
const NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g;
const decodeElem = document.createElement('pre');
/**
* Decodes html encoded text, so that the actual string may
* be used.
* @param value
* @returns {string} decoded text
*/
export function decode(value) {
if (!value) return '';
decodeElem.innerHTML = value.replace(/</g, '<');
return decodeElem.textContent;
}
/**
* Encodes all potentially dangerous characters, so that the
* resulting string can be safely inserted into attribute or
* element text.
* @param value
* @returns {string} encoded text
*/
export function encode(value) {
if (value === null || value === undefined) return '';
return String(value).
replace(/&/g, '&').
replace(SURROGATE_PAIR_REGEXP, value => {
var hi = value.charCodeAt(0);
var low = value.charCodeAt(1);
return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';
}).
replace(NON_ALPHANUMERIC_REGEXP, value => {
return '&#' + value.charCodeAt(0) + ';';
}).
replace(/</g, '<').
replace(/>/g, '>');
}
export default {encode,decode};
javascript에는 HTML Encode/Decode 방식이 없는 것으로 알고 있습니다.
단, JS를 사용하여 임의의 요소를 만들고 내부 텍스트를 설정한 후 내부 텍스트를 사용하여 읽을 수 있습니다.HTML.
예를 들어 jQuery를 사용하면 다음과 같이 동작합니다.
var helper = $('chalk & cheese').hide().appendTo('body');
var htmled = helper.html();
helper.remove();
아니면 이런 식으로요
값을 한 입력 필드에서 다른 입력 필드로 이동하기 위해 이스케이프/엔코딩할 필요가 없습니다.
<form>
<input id="button" type="button" value="Click me">
<input type="hidden" id="hiddenId" name="hiddenId" value="I like cheese">
<input type="text" id="output" name="output">
</form>
<script>
$(document).ready(function(e) {
$('#button').click(function(e) {
$('#output').val($('#hiddenId').val());
});
});
</script>
JS는 raw HTML이나 다른 것을 삽입하지 않습니다.그냥 DOM에 명령어입니다.value
속성(또는 속성, 확실하지 않음)어느 쪽이든 DOM은 부호화 문제를 처리합니다.만약 당신이 이런 이상한 일을 하고 있지 않다면document.write
★★★★★★★★★★★★★★★★★」eval
HTML 코 html html html html html html html html html html html html html 。
결과를 저장하기 위해 새 텍스트 상자를 생성하는 것은 여전히 쉽습니다.HTML의 정적 부분을 jQuery에 전달하고 나머지 속성/속성을 jQuery가 반환하는 개체에 설정합니다.
$box = $('<input type="text" name="whatever">').val($('#hiddenId').val());
도 비슷한 이 요.encodeURIComponent
JavaScript에서 (문서)
예를 들어, 다음 항목을 사용하는 경우:
<input id='hiddenId' type='hidden' value='chalk & cheese' />
그리고.
encodeURIComponent($('#hiddenId').attr('value'))
얻을 수 있다chalk%20%26%20cheese
확보되어 공간도 확보되어 있습니다.
내 경우 백슬래시 하나를 인코딩해야 했고 이 코드는 완벽하게 작동합니다.
encodeURIComponent('name/surname')
그리고 나는 받았다name%2Fsurname
여기 이 부분을 이 있습니다.Server.HTMLEncode
「JavaScript」 「Microsoft ASP」:
function htmlEncode(s) {
var ntable = {
"&": "amp",
"<": "lt",
">": "gt",
"\"": "quot"
};
s = s.replace(/[&<>"]/g, function(ch) {
return "&" + ntable[ch] + ";";
})
s = s.replace(/[^ -\x7e]/g, function(ch) {
return "&#" + ch.charCodeAt(0).toString() + ";";
});
return s;
}
이 결과에서는 아포스트로피는 부호화되지 않지만 다른 HTML 스페셜 및 0x20~0x7e 범위의 임의의 문자가 부호화됩니다.
내 순수 JS 함수:
/**
* HTML entities encode
*
* @param {string} str Input text
* @return {string} Filtered text
*/
function htmlencode (str){
var div = document.createElement('div');
div.appendChild(document.createTextNode(str));
return div.innerHTML;
}
jQuery를 사용하는 경우.이걸 찾았어요
http://www.jquerysdk.com/api/jQuery.htmlspecialchars
(jQuery SDK에서 제공하는 jquery.string 플러그인의 일부)
프로토타입의 문제는 JavaScript에서 기본 객체를 확장하여 사용하던 jQuery와 호환되지 않는다는 것입니다.물론 jQuery가 아닌 프로토타입을 이미 사용하고 있다면 문제 없습니다.
편집: 또한 다음과 같은 jQuery용 프로토타입 문자열 유틸리티 포트도 있습니다.
http://stilldesigning.com/dotstring/
var htmlEnDeCode = (function() {
var charToEntityRegex,
entityToCharRegex,
charToEntity,
entityToChar;
function resetCharacterEntities() {
charToEntity = {};
entityToChar = {};
// add the default set
addCharacterEntities({
'&' : '&',
'>' : '>',
'<' : '<',
'"' : '"',
''' : "'"
});
}
function addCharacterEntities(newEntities) {
var charKeys = [],
entityKeys = [],
key, echar;
for (key in newEntities) {
echar = newEntities[key];
entityToChar[key] = echar;
charToEntity[echar] = key;
charKeys.push(echar);
entityKeys.push(key);
}
charToEntityRegex = new RegExp('(' + charKeys.join('|') + ')', 'g');
entityToCharRegex = new RegExp('(' + entityKeys.join('|') + '|&#[0-9]{1,5};' + ')', 'g');
}
function htmlEncode(value){
var htmlEncodeReplaceFn = function(match, capture) {
return charToEntity[capture];
};
return (!value) ? value : String(value).replace(charToEntityRegex, htmlEncodeReplaceFn);
}
function htmlDecode(value) {
var htmlDecodeReplaceFn = function(match, capture) {
return (capture in entityToChar) ? entityToChar[capture] : String.fromCharCode(parseInt(capture.substr(2), 10));
};
return (!value) ? value : String(value).replace(entityToCharRegex, htmlDecodeReplaceFn);
}
resetCharacterEntities();
return {
htmlEncode: htmlEncode,
htmlDecode: htmlDecode
};
})();
이것은 ExtJS 소스 코드입니다.
<script>
String.prototype.htmlEncode = function () {
return String(this)
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>');
}
var aString = '<script>alert("I hack your site")</script>';
console.log(aString.htmlEncode());
</script>
출력: 언언력 will:<script>alert("I hack your site")</script>
.htmlEncode()는 정의되면 모든 문자열에서 액세스할 수 있습니다.
Html 지정된 값을 인코딩합니다.
var htmlEncodeContainer = $('<div />');
function htmlEncode(value) {
if (value) {
return htmlEncodeContainer.text(value).html();
} else {
return '';
}
}
도메인 백슬래시에 문제가 발생하였습니다.사용자 문자열
아넨트로픽의 대답에서 도망친 다른 탈출에 이걸 추가했어
.replace(/\\/g, '\')
내가 여기서 찾은 건JavaScript에서 백슬래시를 이스케이프하는 방법
escapeHTML()
시제품에서 하고 있습니다.js
이 스크립트를 추가하면 탈출에 도움이 됩니다.HTML:
String.prototype.escapeHTML = function() {
return this.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>')
}
이제 탈출이라고 부를 수 있다.스크립트의 문자열에 대한 HTML 메서드는 다음과 같습니다.
var escapedString = "<h1>this is HTML</h1>".escapeHTML();
// gives: "<h1>this is HTML</h1>"
전체 프로토타입을 포함하지 않고 간단한 솔루션을 찾는 모든 사용자에게 도움이 되기를 바랍니다.js
여기에 다른 중 를 사용하여 문자의 모든 하는 버전을 ('로 뿐).replace()
더 큰 문자열이 더 빠릅니다.
DOM API의 존재나 다른 라이브러리에는 의존하지 않습니다.
window.encodeHTML = (function() {
function escapeRegex(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
var encodings = {
'&' : '&',
'"' : '"',
'\'' : ''',
'<' : '<',
'>' : '>',
'\\' : '/'
};
function encode(what) { return encodings[what]; };
var specialChars = new RegExp('[' +
escapeRegex(Object.keys(encodings).join('')) +
']', 'g');
return function(text) { return text.replace(specialChars, encode); };
})();
한 번 실행했으므로, 이제 전화할 수 있습니다.
encodeHTML('<>&"\'')
<>&"'
function encodeHTML(str) {
return document.createElement("a").appendChild(
document.createTextNode(str)).parentNode.innerHTML;
};
function decodeHTML(str) {
var element = document.createElement("a");
element.innerHTML = str;
return element.textContent;
};
var str = "<"
var enc = encodeHTML(str);
var dec = decodeHTML(enc);
console.log("str: " + str, "\nenc: " + enc, "\ndec: " + dec);
네크로맨싱.
jQuery는 필요 없습니다.
자바스크립트Web.Http 유틸리티(C# - 책지 : 지지지지지지지지지지지지지지 web ) :
"use strict";
function htmlDecode(s) {
if (s == null)
return null;
if (s.length == 0)
return "";
if (s.indexOf('&') == -1)
return s;
function isDigit(str) {
return /^\d+$/.test(str);
}
function isHexDigit(str) {
return /[0-9A-Fa-f]{6}/g.test(str);
}
function initEntities() {
var entities = {};
entities["nbsp"] = '\u00A0';
entities["iexcl"] = '\u00A1';
entities["cent"] = '\u00A2';
entities["pound"] = '\u00A3';
entities["curren"] = '\u00A4';
entities["yen"] = '\u00A5';
entities["brvbar"] = '\u00A6';
entities["sect"] = '\u00A7';
entities["uml"] = '\u00A8';
entities["copy"] = '\u00A9';
entities["ordf"] = '\u00AA';
entities["laquo"] = '\u00AB';
entities["not"] = '\u00AC';
entities["shy"] = '\u00AD';
entities["reg"] = '\u00AE';
entities["macr"] = '\u00AF';
entities["deg"] = '\u00B0';
entities["plusmn"] = '\u00B1';
entities["sup2"] = '\u00B2';
entities["sup3"] = '\u00B3';
entities["acute"] = '\u00B4';
entities["micro"] = '\u00B5';
entities["para"] = '\u00B6';
entities["middot"] = '\u00B7';
entities["cedil"] = '\u00B8';
entities["sup1"] = '\u00B9';
entities["ordm"] = '\u00BA';
entities["raquo"] = '\u00BB';
entities["frac14"] = '\u00BC';
entities["frac12"] = '\u00BD';
entities["frac34"] = '\u00BE';
entities["iquest"] = '\u00BF';
entities["Agrave"] = '\u00C0';
entities["Aacute"] = '\u00C1';
entities["Acirc"] = '\u00C2';
entities["Atilde"] = '\u00C3';
entities["Auml"] = '\u00C4';
entities["Aring"] = '\u00C5';
entities["AElig"] = '\u00C6';
entities["Ccedil"] = '\u00C7';
entities["Egrave"] = '\u00C8';
entities["Eacute"] = '\u00C9';
entities["Ecirc"] = '\u00CA';
entities["Euml"] = '\u00CB';
entities["Igrave"] = '\u00CC';
entities["Iacute"] = '\u00CD';
entities["Icirc"] = '\u00CE';
entities["Iuml"] = '\u00CF';
entities["ETH"] = '\u00D0';
entities["Ntilde"] = '\u00D1';
entities["Ograve"] = '\u00D2';
entities["Oacute"] = '\u00D3';
entities["Ocirc"] = '\u00D4';
entities["Otilde"] = '\u00D5';
entities["Ouml"] = '\u00D6';
entities["times"] = '\u00D7';
entities["Oslash"] = '\u00D8';
entities["Ugrave"] = '\u00D9';
entities["Uacute"] = '\u00DA';
entities["Ucirc"] = '\u00DB';
entities["Uuml"] = '\u00DC';
entities["Yacute"] = '\u00DD';
entities["THORN"] = '\u00DE';
entities["szlig"] = '\u00DF';
entities["agrave"] = '\u00E0';
entities["aacute"] = '\u00E1';
entities["acirc"] = '\u00E2';
entities["atilde"] = '\u00E3';
entities["auml"] = '\u00E4';
entities["aring"] = '\u00E5';
entities["aelig"] = '\u00E6';
entities["ccedil"] = '\u00E7';
entities["egrave"] = '\u00E8';
entities["eacute"] = '\u00E9';
entities["ecirc"] = '\u00EA';
entities["euml"] = '\u00EB';
entities["igrave"] = '\u00EC';
entities["iacute"] = '\u00ED';
entities["icirc"] = '\u00EE';
entities["iuml"] = '\u00EF';
entities["eth"] = '\u00F0';
entities["ntilde"] = '\u00F1';
entities["ograve"] = '\u00F2';
entities["oacute"] = '\u00F3';
entities["ocirc"] = '\u00F4';
entities["otilde"] = '\u00F5';
entities["ouml"] = '\u00F6';
entities["divide"] = '\u00F7';
entities["oslash"] = '\u00F8';
entities["ugrave"] = '\u00F9';
entities["uacute"] = '\u00FA';
entities["ucirc"] = '\u00FB';
entities["uuml"] = '\u00FC';
entities["yacute"] = '\u00FD';
entities["thorn"] = '\u00FE';
entities["yuml"] = '\u00FF';
entities["fnof"] = '\u0192';
entities["Alpha"] = '\u0391';
entities["Beta"] = '\u0392';
entities["Gamma"] = '\u0393';
entities["Delta"] = '\u0394';
entities["Epsilon"] = '\u0395';
entities["Zeta"] = '\u0396';
entities["Eta"] = '\u0397';
entities["Theta"] = '\u0398';
entities["Iota"] = '\u0399';
entities["Kappa"] = '\u039A';
entities["Lambda"] = '\u039B';
entities["Mu"] = '\u039C';
entities["Nu"] = '\u039D';
entities["Xi"] = '\u039E';
entities["Omicron"] = '\u039F';
entities["Pi"] = '\u03A0';
entities["Rho"] = '\u03A1';
entities["Sigma"] = '\u03A3';
entities["Tau"] = '\u03A4';
entities["Upsilon"] = '\u03A5';
entities["Phi"] = '\u03A6';
entities["Chi"] = '\u03A7';
entities["Psi"] = '\u03A8';
entities["Omega"] = '\u03A9';
entities["alpha"] = '\u03B1';
entities["beta"] = '\u03B2';
entities["gamma"] = '\u03B3';
entities["delta"] = '\u03B4';
entities["epsilon"] = '\u03B5';
entities["zeta"] = '\u03B6';
entities["eta"] = '\u03B7';
entities["theta"] = '\u03B8';
entities["iota"] = '\u03B9';
entities["kappa"] = '\u03BA';
entities["lambda"] = '\u03BB';
entities["mu"] = '\u03BC';
entities["nu"] = '\u03BD';
entities["xi"] = '\u03BE';
entities["omicron"] = '\u03BF';
entities["pi"] = '\u03C0';
entities["rho"] = '\u03C1';
entities["sigmaf"] = '\u03C2';
entities["sigma"] = '\u03C3';
entities["tau"] = '\u03C4';
entities["upsilon"] = '\u03C5';
entities["phi"] = '\u03C6';
entities["chi"] = '\u03C7';
entities["psi"] = '\u03C8';
entities["omega"] = '\u03C9';
entities["thetasym"] = '\u03D1';
entities["upsih"] = '\u03D2';
entities["piv"] = '\u03D6';
entities["bull"] = '\u2022';
entities["hellip"] = '\u2026';
entities["prime"] = '\u2032';
entities["Prime"] = '\u2033';
entities["oline"] = '\u203E';
entities["frasl"] = '\u2044';
entities["weierp"] = '\u2118';
entities["image"] = '\u2111';
entities["real"] = '\u211C';
entities["trade"] = '\u2122';
entities["alefsym"] = '\u2135';
entities["larr"] = '\u2190';
entities["uarr"] = '\u2191';
entities["rarr"] = '\u2192';
entities["darr"] = '\u2193';
entities["harr"] = '\u2194';
entities["crarr"] = '\u21B5';
entities["lArr"] = '\u21D0';
entities["uArr"] = '\u21D1';
entities["rArr"] = '\u21D2';
entities["dArr"] = '\u21D3';
entities["hArr"] = '\u21D4';
entities["forall"] = '\u2200';
entities["part"] = '\u2202';
entities["exist"] = '\u2203';
entities["empty"] = '\u2205';
entities["nabla"] = '\u2207';
entities["isin"] = '\u2208';
entities["notin"] = '\u2209';
entities["ni"] = '\u220B';
entities["prod"] = '\u220F';
entities["sum"] = '\u2211';
entities["minus"] = '\u2212';
entities["lowast"] = '\u2217';
entities["radic"] = '\u221A';
entities["prop"] = '\u221D';
entities["infin"] = '\u221E';
entities["ang"] = '\u2220';
entities["and"] = '\u2227';
entities["or"] = '\u2228';
entities["cap"] = '\u2229';
entities["cup"] = '\u222A';
entities["int"] = '\u222B';
entities["there4"] = '\u2234';
entities["sim"] = '\u223C';
entities["cong"] = '\u2245';
entities["asymp"] = '\u2248';
entities["ne"] = '\u2260';
entities["equiv"] = '\u2261';
entities["le"] = '\u2264';
entities["ge"] = '\u2265';
entities["sub"] = '\u2282';
entities["sup"] = '\u2283';
entities["nsub"] = '\u2284';
entities["sube"] = '\u2286';
entities["supe"] = '\u2287';
entities["oplus"] = '\u2295';
entities["otimes"] = '\u2297';
entities["perp"] = '\u22A5';
entities["sdot"] = '\u22C5';
entities["lceil"] = '\u2308';
entities["rceil"] = '\u2309';
entities["lfloor"] = '\u230A';
entities["rfloor"] = '\u230B';
entities["lang"] = '\u2329';
entities["rang"] = '\u232A';
entities["loz"] = '\u25CA';
entities["spades"] = '\u2660';
entities["clubs"] = '\u2663';
entities["hearts"] = '\u2665';
entities["diams"] = '\u2666';
entities["quot"] = '\u0022';
entities["amp"] = '\u0026';
entities["lt"] = '\u003C';
entities["gt"] = '\u003E';
entities["OElig"] = '\u0152';
entities["oelig"] = '\u0153';
entities["Scaron"] = '\u0160';
entities["scaron"] = '\u0161';
entities["Yuml"] = '\u0178';
entities["circ"] = '\u02C6';
entities["tilde"] = '\u02DC';
entities["ensp"] = '\u2002';
entities["emsp"] = '\u2003';
entities["thinsp"] = '\u2009';
entities["zwnj"] = '\u200C';
entities["zwj"] = '\u200D';
entities["lrm"] = '\u200E';
entities["rlm"] = '\u200F';
entities["ndash"] = '\u2013';
entities["mdash"] = '\u2014';
entities["lsquo"] = '\u2018';
entities["rsquo"] = '\u2019';
entities["sbquo"] = '\u201A';
entities["ldquo"] = '\u201C';
entities["rdquo"] = '\u201D';
entities["bdquo"] = '\u201E';
entities["dagger"] = '\u2020';
entities["Dagger"] = '\u2021';
entities["permil"] = '\u2030';
entities["lsaquo"] = '\u2039';
entities["rsaquo"] = '\u203A';
entities["euro"] = '\u20AC';
return entities;
}
var Entities = initEntities();
var rawEntity = [];
var entity = [];
var output = [];
var len = s.length;
var state = 0;
var number = 0;
var is_hex_value = false;
var have_trailing_digits = false;
for (var i = 0; i < len; i++) {
var c = s[i];
if (state == 0) {
if (c == '&') {
entity.push(c);
rawEntity.push(c);
state = 1;
}
else {
output.push(c);
}
continue;
}
if (c == '&') {
state = 1;
if (have_trailing_digits) {
entity.push(number.toString());
have_trailing_digits = false;
}
output.push(entity.join(""));
entity = [];
entity.push('&');
continue;
}
if (state == 1) {
if (c == ';') {
state = 0;
output.push(entity.join(""));
output.push(c);
entity = [];
}
else {
number = 0;
is_hex_value = false;
if (c != '#') {
state = 2;
}
else {
state = 3;
}
entity.push(c);
rawEntity.push(c);
}
}
else if (state == 2) {
entity.push(c);
if (c == ';') {
var key = entity.join("");
if (key.length > 1 && Entities.hasOwnProperty(key.substr(1, key.length - 2)))
key = Entities[key.substr(1, key.length - 2)].toString();
output.push(key);
state = 0;
entity = [];
rawEntity = [];
}
}
else if (state == 3) {
if (c == ';') {
if (number == 0)
output.push(rawEntity.join("") + ";");
else if (number > 65535) {
output.push("&#");
output.push(number.toString());
output.push(";");
}
else {
output.push(String.fromCharCode(number));
}
state = 0;
entity = [];
rawEntity = [];
have_trailing_digits = false;
}
else if (is_hex_value && isHexDigit(c)) {
number = number * 16 + parseInt(c, 16);
have_trailing_digits = true;
rawEntity.push(c);
}
else if (isDigit(c)) {
number = number * 10 + (c.charCodeAt(0) - '0'.charCodeAt(0));
have_trailing_digits = true;
rawEntity.push(c);
}
else if (number == 0 && (c == 'x' || c == 'X')) {
is_hex_value = true;
rawEntity.push(c);
}
else {
state = 2;
if (have_trailing_digits) {
entity.push(number.toString());
have_trailing_digits = false;
}
entity.push(c);
}
}
}
if (entity.length > 0) {
output.push(entity.join(""));
}
else if (have_trailing_digits) {
output.push(number.toString());
}
return output.join("");
}
function htmlEncode(s) {
if (s == null)
return null;
if (s.length == 0)
return s;
var needEncode = false;
for (var i = 0; i < s.length; i++) {
var c = s[i];
if (c == '&' || c == '"' || c == '<' || c == '>' || c.charCodeAt(0) > 159
|| c == '\'') {
needEncode = true;
break;
}
}
if (!needEncode)
return s;
var output = [];
var len = s.length;
for (var i = 0; i < len; i++) {
var ch = s[i];
switch (ch) {
case '&':
output.push("&");
break;
case '>':
output.push(">");
break;
case '<':
output.push("<");
break;
case '"':
output.push(""");
break;
case '\'':
output.push("'");
break;
case '\uff1c':
output.push("<");
break;
case '\uff1e':
output.push(">");
break;
default:
if (ch.charCodeAt(0) > 159 && ch.charCodeAt(0) < 256) {
output.push("&#");
output.push(ch.charCodeAt(0).toString());
output.push(";");
}
else
output.push(ch);
break;
}
}
return output.join("");
}
언급URL : https://stackoverflow.com/questions/1219860/html-encoding-lost-when-attribute-read-from-input-field
'it-source' 카테고리의 다른 글
MySQL 스토어드 프로시저에서의 스토어드 프로시저 호출 (0) | 2022.12.09 |
---|---|
Python이 이 JSON 데이터를 해석할 수 없는 이유는 무엇입니까? (0) | 2022.11.29 |
HMVC 패턴이란 무엇입니까? (0) | 2022.11.29 |
Python void 반환 유형 주석 (0) | 2022.11.29 |
행을 MySQL 데이터베이스에 삽입하는 가장 효율적인 방법 (0) | 2022.11.29 |