decodeURI不会替换编码

huangapple go评论60阅读模式
英文:

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 = &quot;test [u0027] test&quot;;
myText = myText.replace(&quot;\[u&quot;,&quot;\\u&quot;);
myText = myText.replace(&quot;]&quot;,&quot;&quot;)

console.log(decodeURI(myText));

<!-- end snippet -->

It does not replace the by a character. Does anyone have a solution?

答案1

得分: 0

以下是翻译好的内容:

JavaScript代码解释器会解析\u0027语法,并将其转换为一个“真实”的字符串。

这意味着你无法动态构建\u0027,因为&quot;\u&quot;甚至不是一个有效的字符串。

&quot;\\u&quot;是一个有效的字符串,它会被解析为实际的字符串&quot;\u&quot;,但这并不是“魔法”Unicode标记,它只是你看到的样子。

你可以想象一下:

console.log(&quot;\u0027&quot;);

会被转换为:

console.log(&quot;&#39;&quot;);

在JavaScript代码(console.log)实际执行之前。

%27语法可以被动态构建,因为它已经是一个真实的字符串:

decodeURI( &#39;%&#39; + &#39;27&#39; )

另外注意:
也许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 &quot;\u&quot; is not even a valid string.

&quot;\\u&quot; is a valid string, which gets resolved to the actual string &quot;\u&quot;, but that is not the "magic" unicode marker, it's just what you see.

You can imagine it like:

console.log(&quot;\u0027&quot;);

gets converted to:

console.log(&quot;&#39;&quot;);

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( &#39;%&#39; + &#39;27&#39; )

Also Note:

Maybe the String.fromCodePoint function is useful to you:

String.fromCodePoint( 0x27 )

huangapple
  • 本文由 发表于 2023年6月29日 02:46:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76575925.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定