admin管理员组文章数量:1186699
My server returns value as support\testing
. When I get this value in client it can be escaped as support testing
. \t
is escaped as tab space.
How do I avoid escaping special characters in JavaScript?
My server returns value as support\testing
. When I get this value in client it can be escaped as support testing
. \t
is escaped as tab space.
How do I avoid escaping special characters in JavaScript?
Share Improve this question edited Oct 19, 2020 at 7:10 HDJEMAI 9,80048 gold badges76 silver badges98 bronze badges asked Jul 9, 2013 at 15:12 rakyraky 1911 gold badge2 silver badges11 bronze badges 7 | Show 2 more comments5 Answers
Reset to default 14Your server needs to output the string with proper escaping.
In this case, you want a backslash character in the output; backslash is a special character, so that should be escaped.
The escape sequence for a backslash is \\
(ie two backslashes), but you shouldn't need to think about specific escape codes -- if you're outputting JS data, you should be outputting it using proper escaping for the whole string, which generally means you should be using JSON encoding.
Most server languages these days provide JSON encoding as a built-in feature. You haven't specified which language your server is using, but for example if it's written in PHP, you would output your string as json_encode($string)
rather than just outputting $string
directly. Other languages provide a similar feature. This will protect you not just from broken backslash characters, but also from other errors, such as quote marks or line feeds in your strings, which will also cause errors if you put them into a Javascript code as an unescaped string.
You can use tagged template literals
var str = (s => s.raw)`support\testing`[0]
The anonymous arrow function will serve as tag and s.raw
contains the original input
If you are able to change the server-side code, you should add the escape character there: "support\\testing"
.
That will result in the desired result.
You can do a simple replace:
str.replace("\t","\\t");
And do this for other characters you need replacing.
Best Solution for this
function valid(f) {
debugger;
var s = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?~";
str = f.value;
for (var i = 0; i < str.length; i++) {
if (s.indexOf(str.charAt(i)) != -1) {
//alert("The box has special characters. \nThese are not allowed.\n");
f.value = f.value.replace(str.charAt(i), '');// : null;
return false;
}
}
}
本文标签: escapingavoid to escape a special characters in javascriptStack Overflow
版权声明:本文标题:escaping - avoid to escape a special characters in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738344054a2077723.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
"support\\testing"
? See: msdn.microsoft.com/en-us/library/ie/2yfce773(v=vs.94).aspx – i_am_jorf Commented Jul 9, 2013 at 15:14