javascript tutorial - [Solved-5 Solutions] How encoding lost when attribute resd from input field - javascript - java script - javascript array



Problem:

I’m using JavaScript to pull a value out from a hidden field and display it in a textbox. The value in the hidden field is encoded. For example,

<input id='hiddenId' type='hidden' value='chalk & cheese' />
click below button to copy the code. By JavaScript tutorial team

gets pulled into

<input type='text' value='chalk & cheese' />
click below button to copy the code. By JavaScript tutorial team

via some jQuery to get the value from the hidden field (it’s at this point that we lose the encoding):

$('#hiddenId').attr('value')
click below button to copy the code. By JavaScript tutorial team

The problem is that when we read chalk & cheese from the hidden field, JavaScript seems to lose the encoding. To escape " and ', We want the encoding to remain. Is there a JavaScript library or a jQuery method that will HTML-encode a string?

Solution 1:

We use these functions:

function htmlEncode(value){
  // Create a in-memory div, set its inner text (which jQuery automatically encodes)
  // Then grab the encoded contents back out. The div never exists on the page.
  return $('<div/>').text(value).html();
}

function htmlDecode(value){
  return $('<div/>').html(value).text();
}
click below button to copy the code. By JavaScript tutorial team

Basically a div element is created in memory, but it is never appended to the document. On the htmlEncode function we set the innerText of the element, and retrieve the encoded innerHTML; on the htmlDecode function we set the innerHTML value of the element and the innerText is retrieved.

Solution 2:

The jQuery trick doesn't encode quote marks and in IE it will strip our whitespace. Based on the escape templatetag in Django, which we guess is heavily used/tested already, We made this function which does what's needed. It's arguably simpler (and possibly faster) than any of the workarounds for the whitespace-stripping issue - and it encodes quote marks, which is essential if you're going to use the result inside an attribute value for example.

function htmlEscape(str) {
    return str
        .replace(/&/g, '&')
        .replace(/"/g, '"')
        .replace(/'/g, ''')
        .replace(/</g, '<')
        .replace(/>/g, '>');
}

// We needed the opposite function today, so adding here too:
function htmlUnescape(str){
    return str
        .replace(/"/g, '"')
        .replace(/'/g, "'")
        .replace(/</g, '<')
        .replace(/>/g, '>')
        .replace(/&/g, '&');
}
click below button to copy the code. By JavaScript tutorial team

    Update :

  • In the search for the fastest escaping We have found this implementation of a replaceAll method:
  • (also referenced here: Fastest method to replace all instances of a character in a string.
  • Some performance results here:
  • It gives identical result string to the builtin replace chains above.
  • Update :

  • We just noticed that AngularJS are using exactly the method above:
  • They add a couple of refinements - they appear to be handling an obscure Unicode issue as well as converting all non-alphanumeric characters to entities.
  • We was under the impression the latter was not necessary as long as we have an UTF8 charset specified for our document.
  • We will note that (4 years later) Django still does not do either of these things, so I'm not sure how important they are:
  • Update :

  • We may also wish to escape forward-slash /.
  • This is not required for correct HTML encoding, however it is recommended by OWASP as an anti-XSS safety measure. (thanks to @JNF for suggesting this in comments)

Solution 3:

We know this is an old one, but we wanted to post a variation of the accepted answer that will work in IE without removing lines:

function multiLineHtmlEncode(value) {
    var lines = value.split(/\r\n|\r|\n/);
    for (var we = 0; we < lines.length; i++) {
        lines[i] = htmlEncode(lines[i]);
    }
    return lines.join('\r\n');
}

function htmlEncode(value) {
    return $('<div/>').text(value).html();
} 

click below button to copy the code. By JavaScript tutorial team

Solution 4:

Underscore provides _.escape() and _.unescape() methods that do this.

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

> _.escape( "chalk & cheese" );
  "chalk & cheese"
click below button to copy the code. By JavaScript tutorial team

Solution 5:

Note that if the value to encode is undefined or null with jQuery 1.4.2 we might get errors such as:

jQuery("<div/>").text(value).html is not a function
click below button to copy the code. By JavaScript tutorial team

OR

Uncaught TypeError: Object has no method 'html'
click below button to copy the code. By JavaScript tutorial team

The solution is to modify the function to check for an actual value:

function htmlEncode(value){ 
    if (value) {
        return jQuery('<div/>').text(value).html(); 
    } else {
        return '';
    }
}

click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - How-encoding lost when attribute resd from input field