DotBlack
DotBlack

Reputation: 38

Javascript decodeURI makes problems

I wish for some help with decoding.

Given parameter: \u00c4 (real key Ä)

The key is packed in a paramter named: reboundContent[2][id] ( \u00c4 )

reboundContent[2][id] is read from the database.

Next I tried following: decodeURI(reboundContent[2][id]) and that doesn't work.

If I create a new string and pass in the parameter everything works perfectly, but I can't give in that parameter.

That's crazy.

Thanks for help in advance!

Upvotes: 0

Views: 151

Answers (2)

Tomas Langkaas
Tomas Langkaas

Reputation: 4731

From your question and possible solution, it seems that the string containing \u00c4, actually contains the 6 characters "\", "u", "0", "0", "c", and "4".

In order to convert it to the unicode character it is meant to represent, a straightforward approach is to wrap it in quotes and use JSON.parse:

var parsedString = JSON.parse('"' + originalString + '"');

//Set string to "\u00c4", literally.
//Note that the backslash is escaped
//with a preceding backslash
var string = "\\u00c4";

//check string
console.log(string); // \u00c4

//check string length
console.log(string.length); // has 6 characters

//check first two characters
console.log(string.slice(0,2)); //are "\" and "u"

//convert to actual character
string = JSON.parse('"' + string + '"');

//string is now "Ä"
console.log(string);

//works for longer strings also:
console.log(JSON.parse('"\\u00c4 and \\u00d8"')); // Ä and Ø

Using this approach should be far more simple than splitting the string into components, searching for "\u" , deleting the "0"'s and use String.fromCharCode(parseInt('c4', 16));

Upvotes: 1

DotBlack
DotBlack

Reputation: 38

I found a solution. It's more or less good and surely not perfect, but it's a way to solve that.

I was just splitting up the string into it's components. So. I'm looking for the combination \u in the strings I want to check. If that is found I'm deleting all 0 in front to get the right codeword. In this case c4. That can be translated by calling that method. String.fromCharCode(parseInt('c4', 16)); The original string was copied at methodstart and I'm replacing the \u00c4 with the Ä from the method. That can be done with each element in the string.

Upvotes: 0

Related Questions