如何设置带有撇号和引号的javascript变量(不能逃脱它!)

时间:2018-05-10 06:21:35

标签: javascript escaping

我目前正在开展一个项目,我无法访问其服务器端。我所能做的只是从他们的模板编辑器中检索博客数据,但似乎没有办法使用他们的模板语法来逃避HTML。这很糟糕,但我需要在javascript变量中分配HTML来创建Json数据。

在Python中,您使用撇号和引号而不使用三个撇号来转义它:

example = ''' 
            this '/ is great! ""Wahjhahaha
          '''

Javascript中有没有相同的方法?正如我所提到的,我无法逃避HTML数据。

2 个答案:

答案 0 :(得分:0)

" \"是javascript中的转义字符。



var example = "This is a string with \' \" ";
console.log(example);




答案 1 :(得分:0)

根据您的目的,有几种方法。

你可以在双引号中使用单个quoute。

您可以在单引号内使用双引号。

如果你想在双引号中使用双引号,你必须在元素之前使用反斜杠(\)。这同样适用于单引号

console.log('This is double quote inside single quote "');
console.log("This is single quote inside double quote '");
console.log('This is single quote inside single quote \'');
console.log("This is double quote inside double quote \"");
console.log('\' " " \'');
console.log("' \" \" '");

修改

您需要使用函数replace()

var str = "Using single quotes ' ' sdsd 'sd 'dssd sdf' 'sdf'";
str = str.replace(/'/g, "\\'");
console.log(str);

同样,您可以使用双引号。

或者你可以使用反引号,但我不推荐它(backticks in IE11

console.log(`Here you can use both ' single and " double quotes without backslashes`);