英文:
decodeURI doesn't replace encoding
问题
I'm having an issue decoding a string.
var myText = "test [u0027] test";
myText = myText.replace("[u", "\\u");
myText = myText.replace("]", "")
console.log(decodeURI(myText));
It does not replace the [u
by a character. Does anyone have a solution?
英文:
I'm having an issue decoding a string.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
var myText = "test [u0027] test";
myText = myText.replace("\[u","\\u");
myText = myText.replace("]","")
console.log(decodeURI(myText));
<!-- end snippet -->
It does not replace the by a character. Does anyone have a solution?
答案1
得分: 0
以下是翻译好的内容:
JavaScript代码解释器会解析\u0027
语法,并将其转换为一个“真实”的字符串。
这意味着你无法动态构建\u0027
,因为"\u"
甚至不是一个有效的字符串。
"\\u"
是一个有效的字符串,它会被解析为实际的字符串"\u"
,但这并不是“魔法”Unicode标记,它只是你看到的样子。
你可以想象一下:
console.log("\u0027");
会被转换为:
console.log("'");
在JavaScript代码(console.log
)实际执行之前。
%27
语法可以被动态构建,因为它已经是一个真实的字符串:
decodeURI( '%' + '27' )
另外注意:
也许String.fromCodePoint
函数对你有用:
String.fromCodePoint( 0x27 )
英文:
The syntax \u0027
is resolved by the Javascript-code interpreter, which converts it into a "real" string.
That means you can not build the \u0027
dynamically, because "\u"
is not even a valid string.
"\\u"
is a valid string, which gets resolved to the actual string "\u"
, but that is not the "magic" unicode marker, it's just what you see.
You can imagine it like:
console.log("\u0027");
gets converted to:
console.log("'");
before the javascript code (the console.log
) is actually executed.
The %27
syntax can be dynamically built, because it already is a real string:
decodeURI( '%' + '27' )
Also Note:
Maybe the String.fromCodePoint
function is useful to you:
String.fromCodePoint( 0x27 )
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论