HtmlSpecialChars equivalent in Javascript?

后端 未结 16 1545
耶瑟儿~
耶瑟儿~ 2020-11-22 06:00

Apparently, this is harder to find than I thought it would be. And it even is so simple...

Is there a function equivalent to PHP\'s htmlspecialchars built into Javas

16条回答
  •  醉酒成梦
    2020-11-22 06:25

    Chances are you don't need such a function. Since your code is already in the browser*, you can access the DOM directly instead of generating and encoding HTML that will have to be decoded backwards by the browser to be actually used.

    Use innerText property to insert plain text into the DOM safely and much faster than using any of the presented escape functions. Even faster than assigning a static preencoded string to innerHTML.

    Use classList to edit classes, dataset to set data- attributes and setAttribute for others.

    All of these will handle escaping for you. More precisely, no escaping is needed and no encoding will be performed underneath**, since you are working around HTML, the textual representation of DOM.

    // use existing element
    var author = 'John "Superman" Doe ';
    var el = document.getElementById('first');
    el.dataset.author = author;
    el.textContent = 'Author: '+author;
    
    // or create a new element
    var a = document.createElement('a');
    a.classList.add('important');
    a.href = '/search?q=term+"exact"&n=50';
    a.textContent = 'Search for "exact" term';
    document.body.appendChild(a);
    
    // actual HTML code
    console.log(el.outerHTML);
    console.log(a.outerHTML);
    .important { color: red; }

    * This answer is not intended for server-side JavaScript users (Node.js, etc.)

    ** Unless you explicitly convert it to actual HTML afterwards. E.g. by accessing innerHTML - this is what happens when you run $('

    ').text(value).html(); suggested in other answers. So if your final goal is to insert some data into the document, by doing it this way you'll be doing the work twice. Also you can see that in the resulting HTML not everything is encoded, only the minimum that is needed for it to be valid. It is done context-dependently, that's why this jQuery method doesn't encode quotes and therefore should not be used as a general purpose escaper. Quotes escaping is needed when you're constructing HTML as a string with untrusted or quote-containing data at the place of an attribute's value. If you use the DOM API, you don't have to care about escaping at all.

提交回复
热议问题