简体   繁体   English

在js中转义javascript实体?

[英]Escaping javascript entities in js?

I want to escape javascript entities on client side. 我想在客户端转义javascript实体。 For example :- 例如 :-

If my input string is tes"t result should be tes\\"t 如果我的输入字符串是tes"t结果应该是tes\\"t

Is there any inbuilt function provided by jquery for this ? jQuery是否为此提供了任何内置函数?

This is a really crazy, almost stupid shot in the dark on my part, but... 这对我来说是一个非常疯狂的几乎是愚蠢的黑暗拍摄,但是...

If you're using a server-side language like PHP to output variables' contents into JavaScript, you should use json_encode as this handles ALL escaping for you, regardless of the type of variable. 如果您正在使用PHP之类的服务器端语言将变量的内容输出到JavaScript,则应使用json_encode因为这将为您处理所有转义,而不管变量的类型如何。

On the other hand, if you're (I really hope you're not) doing something like this: 另一方面,如果您(我确实希望您不这样做)正在执行以下操作:

var input = "test"t";

And trying to escape that properly while in JavaScript... that's not going to work. 并试图在JavaScript中正确地转义它……这是行不通的。 It's a syntax error. 这是语法错误。 You need to escape your literals manually. 您需要手动转义文字。

Kevin van Zonneveld provide a JavaScript equivalent of PHP's addslashes here : Kevin van Zonneveld在此处提供的JavaScript与PHP的addslashes等效:
http://phpjs.org/functions/addslashes/ http://phpjs.org/functions/addslashes/

function addslashes(str) {
    //   example 1: addslashes("kevin's birthday");
    //   returns 1: "kevin\\'s birthday"

    return (str + '')
    .replace(/[\\"']/g, '\\$&')
    .replace(/\u0000/g, '\\0');
}

Based on this function, I guess you might want to add this function to prototype of the String like this. 基于此功能,我想您可能希望将此功能添加到String prototype中,如下所示。

if (!String.prototype.addslashes) {
   String.prototype.addslashes = function () {
       return this.replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
   };
}

var str = 'tes"t';
alert(str.addslashes()); // shows 'tes\"t'

DEMO: http://jsfiddle.net/naokiota/6F6aN/6/ 演示: http : //jsfiddle.net/naokiota/6F6aN/6/

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM