[英]Javascript How to escape \u in string literal
Strange thing... 奇怪的事情...
I have a string literal that is passed to my source code as a constant token (I cannot prehandle or escape it beforehand). 我有一个字符串常量,它会作为常量标记传递给我的源代码(我无法预先处理或转义它)。
Example 例
var username = "MYDOMAIN\tom";
username = username.replace('MYDOMAIN','');
The string somewhere contains a backslash followed by a character. 该字符串在某处包含反斜杠,后跟一个字符。 It's too late to escape the backslash at this point, so I have to escape these special characters individually like 现在转义反斜线为时已晚,因此我必须分别转义这些特殊字符,例如
username = username.replace(/\t/ig, 't');
However, that does not work in the following scenario: 但是,这在以下情况下不起作用:
var username = "MYDOMAIN\ulrike";
\\u seems to introduce a unicode character sequence. \\ u似乎引入了Unicode字符序列。 \\uLRIK cannot be interpreted as a unicode sign so the Javascript engine stops interpreting at this point and my replace(/\\u/ig,'u') comes too late. \\ uLRIK不能解释为unicode符号,因此Javascript引擎此时停止解释,并且我的replace(/ \\ u / ig,'u')来不及了。
Has anybody a suggestion or workaround on how to escape such a non-unicode character sequence contained in a given string literal? 是否有人对如何转义给定字符串文字中包含的非Unicode字符序列有任何建议或解决方法? It seems a similar issue with \\b like in "MYDOMAIN\\bernd". \\ b似乎存在类似的问题,例如“ MYDOMAIN \\ bernd”中的问题。
I have a string literal that is passed to my source code 我有一个字符串文字传递给我的源代码
Assuming you don't have any < or >, move this to inside an HTML control (instead of inside your script block) or element and use Javacript to read the value. 假设您没有任何<或>,请将其移至HTML控件(而不是脚本块内)或元素内,然后使用Javacript读取值。 Something like 就像是
<div id="myServerData">
MYDOMAIN\tom
</div>
and you retrieve it so 然后您将其检索到
alert(document.getElementById("myServerData").innerText);
IMPORTANT : injecting unescaped content, where the user can control the content (say this is data entered in some other page) is a security risk. 重要说明 :注入未经转义的内容(用户可以在其中控制内容)(例如,这是在其他页面中输入的数据)会带来安全风险。 This goes for whether you are injecting it in script or HTML 无论您是以脚本还是HTML注入
Writing var username = "MYDOMAIN\\ulrike";
编写var username = "MYDOMAIN\\ulrike";
will throw a syntax error. 将抛出语法错误。 I think you have this string coming from somewhere. 我认为您有这个字符串来自某个地方。
I would suggest creating some html element and setting it's innerHTML to the received value, and then picking it up. 我建议创建一些html元素并将其innerHTML设置为接收的值,然后将其拾取。
Have something like: 有类似的东西:
<div id="demo"></div>
Then do document.getElementById("demo").innerHTML = username;
然后执行document.getElementById("demo").innerHTML = username;
Then read the value from there as document.getElementById("demo").innerHTML;
然后从那里读取值为document.getElementById("demo").innerHTML;
This should work I guess. 我猜这应该工作。
Important: Please make sure this does not expose the webpage to script injections. 重要:请确保这不会使网页暴露给脚本注入。 If it does, this method is bad, don't use it. 如果是这样,则此方法不好,请不要使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.