Skip to main content
Inspiring
June 28, 2023
Answered

Issue decoding a string

Hi,

 

I'm having issues decoding a string ...

var newText = "This is a [u0027] test";
newText = newText.replace("\[u", '\\u');
newText = newText.replace("]", "");
newText = decodeURI(newText);
alert(newText);

The base string contains square brackets and lacks the backspace prefix.

 

This however seem to work ...

var newText = "This is a \u0027 test";
newText = decodeURI(newText);

alert(newText);

 

Does aynone have a solution?

 

Thanx

 

This topic is closed to new replies. Start a new post to keep the conversation going.
Peter Kahrel
Peter KahrelCorrect answer
Community Expert
June 28, 2023

To get a string from a Unicode number you'd use 

 

String.fromCharCode (0x0027);

 

You can't use this construct as the replacement value in a replace() call, but you can use a function as the replacement parameter:

 

 

var newText = "This is a [u0027] test";
newText = newText.replace (/\[u(....)\]/, function () {
  return String.fromCharCode ('0x'+arguments[1]);
});
newText = decodeURI(newText);
alert(newText);

 

 

But in fact there is no need to decodeURI newText, you can delete than line.

 

P.

4 replies

Peter Kahrel
Community Expert
Peter KahrelCommunity ExpertCorrect answer
Community Expert
June 28, 2023

To get a string from a Unicode number you'd use 

 

String.fromCharCode (0x0027);

 

You can't use this construct as the replacement value in a replace() call, but you can use a function as the replacement parameter:

 

 

var newText = "This is a [u0027] test";
newText = newText.replace (/\[u(....)\]/, function () {
  return String.fromCharCode ('0x'+arguments[1]);
});
newText = decodeURI(newText);
alert(newText);

 

 

But in fact there is no need to decodeURI newText, you can delete than line.

 

P.

Translate
tmmlsAuthor
Inspiring
June 28, 2023

Thanks Peter. Works perfectly!

 

Translate
brian_p_dts
Community Expert
Community Expert
June 28, 2023

I think no need to escape [ in first replace? Or escape ] in second replace?

Translate
tmmlsAuthor
Inspiring
June 28, 2023

the replacement of the brackets works fine. But it doesn't seem to decode the result ...

Translate