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?
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?
You need to use Javascript escapes for the Unicode characters:
node.nodeValue="string with \uxxxx sort of characters"
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>
<div id="test"> </div>
</body>
<script type="text/javascript">
onload = function()
{
var node = document.getElementById( 'test' );
node.firstChild.nodeValue = convertEntities( 'Some » entities « and some » more entities «' );
}
function convertEntities( 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;
function convertEntity( ent )
{
var num = parseInt(ent.replace(/\D/g, ''), 16);
var esc = ((num < 16) ? '0' : '') + num.toString(16);
return String.fromCharCode( esc );
}
}
</script>
</html>
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:
function convertEntities( text )
{
var ret = text.replace( /\&\#(\d+);/g, function ( ent, captureGroup )
{
var num = parseInt( captureGroup );
return String.fromCharCode( num );
});
return ret;
}