避免在javascript中转义特殊字符 [英] avoid to escape a special characters in javascript

查看:1925
本文介绍了避免在javascript中转义特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的服务器返回值 support\testing 。当我在客户端获得此值时,它可以作为支持测试进行转义。 \t 作为标签空间进行转义。

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.

如何避免转义JavaScript中的特殊字符?

How do I avoid escaping special characters in JavaScript?

推荐答案

您的服务器需要输出正确转义的字符串。

Your server needs to output the string with proper escaping.

在此case,你想在输出中加一个反斜杠字符;反斜杠是一个特殊字符,因此应该进行转义。

In this case, you want a backslash character in the output; backslash is a special character, so that should be escaped.

反斜杠的转义序列是 \\ (即两个反斜杠),但你不需要考虑特定的转义码 - 如果你输出JS数据,你应该使用适当的转义为整个字符串输出它,这通常意味着你应该使用JSON编码。

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.

如今,大多数服务器语言都提供JSON编码作为内置功能。您没有指定服务器使用的语言,但是例如,如果它是用PHP编写的,您可以将字符串输出为 json_encode($ string)而不是仅输出 $ string 直接。其他语言提供类似的功能。这不仅可以保护您免受破坏的反斜杠字符的影响,还可以保护您的其他错误,例如字符串中的引号或换行符,如果您将它们作为非转义字符串放入Javascript代码中,也会导致错误。

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.

这篇关于避免在javascript中转义特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆