tags:

views:

12

answers:

1

how to convert &#(no); embedded in a string to a string with corresponding character in javascript?

+1  A: 
theString.replace(/&#x([0-9a-f]+);/ig, function(s, code) {
  return String.fromCharCode(parseInt(code, 16));
})

Similar for decimal (&#(\d+);).

For entities (©) you need a look-up table.


Why not just directly display the string as HTML anyway? Just strip all the < and > if you want to avoid XSS.

KennyTM
actually i am a beginner, i am using textarea container to do html_entity_decode function, but it is not converting these spl. characters.displaying as such.
Kumar
what is s,code in the function?where we are using s?
Kumar
@KK: I see. In JS, `.replace` can accept a function as the replacement. If a function is provided, the arguments are feed as (1) the whole matched text (i.e. `ꯍ`), and (2) the 1st capture group (`ABCD`), (3) the 2nd capture group etc. Since the whole matched text is not useful, we just ignore it.
KennyTM
i am still having doubt,what is s and what is code?you are mentioning so many groups , whether all are passed as array?
Kumar
@KK: Do you know regular expression?
KennyTM