Some characters in our database are stored in NCR (example 台
(台)).
I need to be able to show them in an alert
window, so I need to translate the value to something that JavaScript can show.
How can I do this?
Some characters in our database are stored in NCR (example 台
(台)).
I need to be able to show them in an alert
window, so I need to translate the value to something that JavaScript can show.
How can I do this?
A simple solution is to use String.fromCharCode()
on just the numeric value.
The static
String.fromCharCode()
method returns a string created by using the specified sequence of Unicode values.
First you'll need to strip the &#
. We can do this with JavaScript's replace()
method:
var symbol = "台".replace("&#", "");
Then we can pass it into String.fromCharCode()
:
alert(String.fromCharCode(symbol));
var symbol = "台".replace("&#", "");
alert(String.fromCharCode(symbol));
...the only problem is that has mixed content. For example: "12 Amp. Street 台"
– Panos K.
For this we can use a regular expression to match the symbol and replace it in-line.
var str = "12 Amp. Street 台";
For this I'm going to use the regular expression /&#(\d*)/
, which matches the combination of "&#" followed by a group of any number of digits. Calling replace()
as we did before, we can instead replace with a function which has two parameters: match
, the entire match (台
) and number
, the group of numbers (21488
). From here we simply return String.fromCharCode(number)
:
var replaced = str.replace(/&#(\d*)/g, function(match, number) {
return String.fromCharCode(number);
});
replaced
should now contain the value "12 Amp. Street 台"
.
var str = "12 Amp. Street 台";
var replaced = str.replace(/&#(\d*)/g, function(match, number) {
return String.fromCharCode(number);
});
alert(replaced);