문제

나 JavaScript 를 사용하여 당겨하는 값에서 숨겨진된 필드 표시할 텍스트 상자.값에 숨겨진 필드를 인코딩됩니다.

예를 들어,

<input id='hiddenId' type='hidden' value='chalk &amp; cheese' />

도로

<input type='text' value='chalk &amp; cheese' />

을 통해 어떤 jQuery 값을 얻기 위해서 숨겨진된 필드(그것은이 시점에서 잃고 인코딩):

$('#hiddenId').attr('value')

문제는 내가 읽을 때 chalk &amp; cheese 에서 숨겨진 분야,자바 스크립트를 잃을 것으로 보인다 encoding.내가 원하지 않을 수 있는 가치 chalk & cheese.내가 원하는 문자 amp; 을 유지 될 수있다.

거기에 자바스크립트 라이브러리 또는 jQuery 방법을 것입니다 HTML 문자열을 인코딩?

도움이 되었습니까?

해결책

편집하다: 이 답변은 오래 전에 게시되었으며 htmlDecode 함수는 XSS 취약점을 도입했습니다. 임시 요소를 div a textarea XSS 기회 감소. 그러나 요즘에는 제안 된대로 Domparser API를 사용하도록 권장합니다. 다른 Anwswer.


나는이 기능을 사용합니다.

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();
}

기본적으로 DIV 요소는 메모리에서 생성되지만 문서에 절대 추가되지 않습니다.

htmlEncode 기능을 설정합니다 innerText 요소의 및 인코딩 된 것을 검색합니다 innerHTML; 에 htmlDecode 기능을 설정합니다 innerHTML 요소의 가치와 innerText 검색됩니다.

실행중인 예제를 확인하십시오 여기.

다른 팁

JQuery 속하지 않는 인코딩 견적 마크 및에서 즉 그것은 지구의 공백.

에 따라 templatetag 장고에서는 많이 사용되는 테스트/이미 이 기능은 무엇이 필요합니다.

그것은 틀림없이 간단(아마도 빨리)보다는 어떠한 해결 방법에 대해 공백을 벗기는 문제는-그리고 그것은 인코딩하는 따옴표는 필수적인 경우에 당신을 사용하여 결과 내부의 특성에 대한 값은 예입니다.

function htmlEscape(str) {
    return str
        .replace(/&/g, '&amp;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;');
}

// I needed the opposite function today, so adding here too:
function htmlUnescape(str){
    return str
        .replace(/&quot;/g, '"')
        .replace(/&#39;/g, "'")
        .replace(/&lt;/g, '<')
        .replace(/&gt;/g, '>')
        .replace(/&amp;/g, '&');
}

업데이트 2013-06-17:
검색에 대한 가장 빠른 탈출하는 난 이야기의 구현 replaceAll 방법:
http://dumpsite.com/forum/index.php?topic=4.msg29#msg29
(또한 여기에 참조: 가장 빠른 방법을 모두 교체하의 인스턴스에서 문자열)
성능 여기 결과:
http://jsperf.com/htmlencoderegex/25

그것은 동일한 결과 문자열을 내장 replace 체인다.나는 매우 행복할 수 있는 사람이 있다는 이유를 설명 빠르다!?

업데이트 2015-03-04:
다련을 사용하는 정확한 방법을 사용:
https://github.com/angular/angular.js/blob/v1.3.14/src/ngSanitize/sanitize.js#L435

그들은 몇 분류-그들은 나타나 처리 모 유니코드 문제 뿐만 아니라 변환 모든 영숫자 문자가 아닌 문자를 entities.미국에서 후자는 필요한 만큼 당신가 UTF8 문자셋을 지정한 당신의 문서입니다.

내가 주는(4 년 이상)장고 여전히지 않는 이러한 것들,그래서 나는 확실하지 않다 그들이 얼마나 중요한다:
https://github.com/django/django/blob/1.8b1/django/utils/html.py#L44

업데이트 2016-04-06:
수도 있습니다 탈출하는 슬래시 /.이 필요하지 않습에 대한 올바른 HTML 로 인코딩,그러나 그것은 권장하는 OWASP 로 anti-XSS 안전 측정값입니다.(덕분에@JNF 제안에 대한 이견에)

        .replace(/\//g, '&#x2F;');

다음은 jQuery보다 상당히 빠른 비 JQuery 버전입니다. .html() 버전과 .replace() 버전. 이것은 모든 공백을 보존하지만 jQuery 버전과 마찬가지로 따옴표를 처리하지 않습니다.

function htmlEncode( html ) {
    return document.createElement( 'a' ).appendChild( 
        document.createTextNode( html ) ).parentNode.innerHTML;
};

속도: http://jsperf.com/htmlencodeergex/17

speed test

데모: jsFiddle

산출:

output

스크립트:

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>   &amp; hello</div>';
document.getElementById( 'same' ).textContent = 
      'html === htmlDecode( htmlEncode( html ) ): ' 
    + ( html === htmlDecode( htmlEncode( html ) ) );

HTML :

<input id="hidden" type="hidden" value="chalk    &amp; 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();
} 

밑줄 제공 _.escape() 그리고 _.unescape() 이를 수행하는 방법.

> _.unescape( "chalk &amp; cheese" );
  "chalk & cheese"

> _.escape( "chalk & cheese" );
  "chalk &amp; cheese"

좋은 대답. 인코딩 값이있는 경우에 유의하십시오 undefined 또는 null 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, 인코딩이 손실되지 않습니다. 인코딩은 페이지로드 중에 Markup Parser (브라우저)가 사용합니다. 소스를 읽고 구문 분석하고 브라우저에 DOM이 메모리에로드되면 인코딩은 그 표현에 따라 구문 분석되었습니다. 따라서 JS가 메모리에서 무엇이든 읽기 위해 실행될 때까지, 그것이 얻는 숯은 인코딩이 나타내는 것입니다.

나는 여기서 의미론에 대해 엄격하게 작동하고 있지만 인코딩의 목적을 이해하기를 원했습니다. "잃어버린"이라는 단어는 무언가가 작동하지 않는 것처럼 들립니다.

원기 내장되어 있습니다 문자열 클래스. 따라서 프로토 타입을 사용하기 위해/계획을 사용하는 경우 다음과 같은 작업을 수행합니다.

'<div class="article">This is an article</div>'.escapeHTML();
// -> "&lt;div class="article"&gt;This is an article&lt;/div&gt;"

jQuery없이 더 빠릅니다. 문자열의 모든 문자를 인코딩 할 수 있습니다.

function encode(e){return e.replace(/[^]/g,function(e){return"&#"+e.charCodeAt(0)+";"})}

또는 주인공을 대상으로 걱정할 수 있습니다 (&, inebreaks, <,>, "및 ')와 같은 :

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 &ampersand (it has to be first),
* \x0A is newline,
*************/
<textarea id=test rows="9" cols="55"></textarea>

<div id="testing">www.WHAK.com</div>

다음은 간단한 JavaScript 솔루션입니다. 매개 변수가없는 객체 또는 매개 변수와 함께 사용할 수있는 메소드 "htmlencode"로 문자열 객체를 확장합니다.

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("æåøåæå"))

나는 만들었다 GIST "JavaScript 용 htmlencode 메소드".

기반 Angular 's Sanitize... (ES6 모듈 구문)

// 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, '&lt;');
  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, '&amp;').
    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, '&lt;').
    replace(/>/g, '&gt;');
}

export default {encode,decode};

afaik JavaScript에는 간단한 HTML Encode/Decode 메소드가 없습니다.

그러나 할 수있는 것은 JS를 사용하여 임의의 요소를 만들고 내부 텍스트를 설정 한 다음 InnerHTML을 사용하여 읽는 것입니다.

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의 정적 부분을 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

내 퓨어 -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;
}

JavaScript HTML 엔티티 인코딩 및 디코딩

jQuery를 사용하려면. 나는 이것을 찾았다:

http://www.jquerysdk.com/api/jquery.htmlspecialchars

(jQuery.String 플러그인의 일부 JQuery SDK가 제공합니다)

프로토 타입의 문제점은 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({
            '&amp;'     :   '&',
            '&gt;'      :   '>',
            '&lt;'      :   '<',
            '&quot;'    :   '"',
            '&#39;'     :   "'"
        });
    }

    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, '&amp;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;');

}

var aString = '<script>alert("I hack your site")</script>';
console.log(aString.htmlEncode());
</script>

출력 : &lt;script&gt;alert(&quot;I hack your site&quot;)&lt;/script&gt;

.htmlencode ()는 한 번 정의 된 모든 문자열에서 액세스 할 수 있습니다.

htmlencodes 주어진 값

  var htmlEncodeContainer = $('<div />');
  function htmlEncode(value) {
    if (value) {
      return htmlEncodeContainer.text(value).html();
    } else {
      return '';
    }
  }

내 도메인 사용자 문자열에서 백 슬래시와 관련된 몇 가지 문제를 해결했습니다.

나는 이것을 Annentropic의 대답에서 다른 탈출에 추가했습니다.

.replace(/\\/g, '&#92;')

내가 여기서 찾은 것 :JavaScript에서 백 슬래시를 피하는 방법?

여기에 에뮬레이션하는 약간이 있습니다 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 범위 외부의 문자를 인코딩합니다.

무엇을 선택합니다 escapeHTML() 프로토 타입에서 수행하고 있습니다 .JS

이 스크립트를 추가하면 EscapeHtml :

String.prototype.escapeHTML = function() { 
    return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;')
}

이제 스크립트의 문자열에서 EscapeHtml 메소드를 호출 할 수 있습니다.

var escapedString = "<h1>this is HTML</h1>".escapeHTML();
// gives: "&lt;h1&gt;this is HTML&lt;/h1&gt;"

전체 프로토 타입을 포함시키지 않고 간단한 솔루션을 찾는 사람에게 도움이되기를 바랍니다.

다른 답변 중 일부를 사용하여 여기에서 나는 고유 한 인코딩 된 문자의 수에 관계없이 한 패스의 모든 관련 문자를 대체하는 버전을 만들었습니다 (하나의 호출 만 replace()) 더 큰 문자열의 경우 더 빠릅니다.

DOM API가 존재하거나 다른 라이브러리에 의존하지 않습니다.

window.encodeHTML = (function() {
    function escapeRegex(s) {
        return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
    }
    var encodings = {
        '&'  : '&amp;',
        '"'  : '&quot;',
        '\'' : '&#39;',
        '<'  : '&lt;',
        '>'  : '&gt;',
        '\\' : '&#x2F;'
    };
    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('<>&"\'')

얻기 위해 &lt;&gt;&amp;&quot;&#39;

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);

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top