how to convert &#(no); embedded in a string to a string with corresponding character in javascript?
views:
12answers:
1
Q:
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
2010-05-21 09:30:27
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
2010-05-21 09:36:33
what is s,code in the function?where we are using s?
Kumar
2010-05-21 09:40:53
@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
2010-05-21 09:56:23
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
2010-05-21 10:38:44
@KK: Do you know regular expression?
KennyTM
2010-05-21 10:40:57