Skip to content Skip to sidebar Skip to footer

Setting Nodevalue Of Text Node In Javascript When String Contains Html Entities

When I set a value of a text node with node.nodeValue='string with &#xxxx; sort of characters' ampersand gets escaped. Is there an easy way to do this?

Solution 1:

You need to use Javascript escapes for the Unicode characters:

node.nodeValue="string with \uxxxx sort of characters"

Solution 2:

The reason this is happening is because the & in your string is being expanded into the ampersand entity by the browser. To get around this, you'll need to convert the entities yourself.

<html><body><divid="test"></div></body><scripttype="text/javascript">

onload = function()
{
    var node = document.getElementById( 'test' );
    node.firstChild.nodeValue = convertEntities( 'Some &#187; entities &#171; and some &#187; more entities &#171;' );
}

functionconvertEntities( text )
{
    var matches = text.match( /\&\#(\d+);/g );

    for ( var i = 0; i < matches.length; i++ )
    {
        console.log( "Replacing: " + matches[i] );
        console.log( "With: " + convertEntity( matches[i] ) );
        text = text.replace( matches[i], convertEntity( matches[i] ) );
    }

    return text;

    functionconvertEntity( ent )
    {
        var num = parseInt(ent.replace(/\D/g, ''), 16);
        var esc = ((num < 16) ? '0' : '') + num.toString(16);
        returnString.fromCharCode( esc );
    }
}

</script></html>

Solution 3:

As noted in other answers, I need to replace html encoded entities with javascript encoded ones. Starting from BaileyP's answer, I've made this:

functionconvertEntities( text )
{
    var ret = text.replace( /\&\#(\d+);/g, function ( ent, captureGroup )
    {
        var num = parseInt( captureGroup );
        returnString.fromCharCode( num );
    });
    return ret;
}

Post a Comment for "Setting Nodevalue Of Text Node In Javascript When String Contains Html Entities"