Hướng dẫn html escape

I want to display text to HTML by a JavaScript function. How can I escape HTML special characters in JavaScript? Is there an API?

asked Jun 4, 2011 at 4:50

3

Here's a solution that will work in practically every web browser:

function escapeHtml[unsafe]
{
    return unsafe
         .replace[/&/g, "&"]
         .replace[//g, ">"]
         .replace[/"/g, """]
         .replace[/'/g, "'"];
 }

If you only support modern web browsers [2020+], then you can use the new replaceAll function:

const escapeHtml = [unsafe] => {
    return unsafe.replaceAll['&', '&'].replaceAll['', '>'].replaceAll['"', '"'].replaceAll["'", '''];
}

dthree

18.8k14 gold badges70 silver badges103 bronze badges

answered Jun 4, 2011 at 5:00

bjorndbjornd

21.8k4 gold badges54 silver badges71 bronze badges

13

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] ];
}];

vsync

107k53 gold badges285 silver badges370 bronze badges

answered Aug 20, 2014 at 2:50

spiderlamaspiderlama

1,44314 silver badges10 bronze badges

2

You can use jQuery's .text[] function.

For example:

//jsfiddle.net/9H6Ch/

From the jQuery documentation regarding the .text[] function:

We need to be aware that this method escapes the string provided as necessary so that it will render correctly in HTML. To do so, it calls the DOM method .createTextNode[], does not interpret the string as HTML.

Previous Versions of the jQuery Documentation worded it this way [emphasis added]:

We need to be aware that this method escapes the string provided as necessary so that it will render correctly in HTML. To do so, it calls the DOM method .createTextNode[], which replaces special characters with their HTML entity equivalents [such as < for 'fred, barney, & pebbles'

Source code

answered Oct 30, 2016 at 19:41

cs01cs01

4,8691 gold badge27 silver badges28 bronze badges

3

I think I found the proper way to do it...

// 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];

answered Aug 7, 2013 at 16:16

lvellalvella

11.9k11 gold badges49 silver badges97 bronze badges

4

This is, by far, the fastest way I have seen it done. Plus, it does it all without adding, removing, or changing elements on the page.

function escapeHTML[unsafeText] {
    let div = document.createElement['div'];
    div.innerText = unsafeText;
    return div.innerHTML;
}

answered Jan 2, 2018 at 0:11

arjunpatarjunpat

5794 silver badges10 bronze badges

4

It was interesting to find a better solution:

var escapeHTML = function[unsafe] {
  return unsafe.replace[/[&' +
  escapeHTML['alert["inspect the attributes"]\u003C/script>'] +
  ''

You should verify the entity ranges I have provided to validate the safety of the function yourself. You could also use this regular expression which has better readability and should cover the same character codes, but is about 10% less performant in my browser:

/[?![0-9A-Za-z]][\u0000-\u00FF]/g

answered Mar 4, 2021 at 19:40

ADJenksADJenks

2,51924 silver badges31 bronze badges

0

If you already use modules in your application, you can use escape-html module.

import escapeHtml from 'escape-html';
const unsafeString = 'alert["XSS"];';
const safeString = escapeHtml[unsafeString];

answered Mar 11, 2020 at 15:13

Shimon SShimon S

3,7782 gold badges26 silver badges33 bronze badges

I 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 */

answered Jul 30, 2019 at 8:36

SilasSilas

111 bronze badge

Just write the code in between

....
. Make sure you add the class name in the code tag. It will escape all the HTML snippet written in
....
.

const escape = {
    '"': '"',
    '&': '&',
    '': '>',
}
const codeWrappers = document.querySelectorAll['.html-escape']
if [codeWrappers.length > 0] {
    codeWrappers.forEach[code => {
        const htmlCode = code.innerHTML
        const escapeString = htmlCode.replace[/"|&|/g, function [matched] {
            return escape[matched];
        }];
        code.innerHTML = escapeString
    }]
}
    
        

Card Title

Srcondary text

Greyhound divisively hello coldly wonderfully marginally far upon excluding.

Go to Go to

answered Apr 14, 2021 at 8:41

Use this to remove HTML tags from a string in JavaScript:

const strippedString = htmlString.replace[/[]+]>]/gi, ""];

console.log[strippedString];

answered Sep 10, 2020 at 14:40

1

Try this, using the prototype.js library:

string.escapeHTML[];

Try a demo

JD.

2,9852 gold badges25 silver badges37 bronze badges

answered Apr 16, 2014 at 20:48

LuckyLucky

7152 gold badges10 silver badges27 bronze badges

1

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 alert["oops"]; here';

var html = '';
html += '
'; html += '

' + unsafe + '

'; html += '
'; 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 alert["oops"]; here';

var html = '';
html += '
'; html += '

' + $[document.createElement['div']].html[unsafe].text[]; + '

'; html += '
'; element.html[html];

To me this is much easier than using .replace[] and it'll remove!!! all possible HTML tags [I hope].

answered Mar 30, 2016 at 9:53

KostiantynKostiantyn

1,5561 gold badge14 silver badges20 bronze badges

2

Chủ Đề