【问题标题】:How to set up a javascript variable with apostrophes and quotations marks (Can't escape it!)如何设置带有撇号和引号的 javascript 变量(无法转义!)
【发布时间】:2018-10-20 08:39:32
【问题描述】:

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

在 Python 中,您可以同时使用撇号和引号,而无需通过使用三个撇号将其转义:

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

在 Javascript 中是否有任何等效的方法?正如我所提到的,我无法转义 HTML 数据。

【问题讨论】:

  • 如果浏览器兼容性不是问题,那么您可以使用 backtip `,但这无疑是一个巨大的安全风险。如果你能得到它作为 JSON...
  • 你好马蒙!谢谢回复。示例是 Python。我看到它必须是'/,但我给你一个例子,它可以在 Python 中不转义它工作。谢谢!
  • @AdrianoRepetti 浏览器兼容性从不成为问题。使用转译器并停止关心......
  • javascript 中的转义字符是\`, not a /` - 显然它必须在要转义的字符之前
  • @baao 如果 OP 正在使用一些奇怪的自制模板引擎(我无法想象这个问题的任何其他原因),那么转译器可能不是一个选项

标签: javascript escaping


【解决方案1】:

“\”是javascript中的转义字符。

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

【讨论】:

    【解决方案2】:

    有几种方法取决于你想做什么。

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

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

    如果要在双引号内使用双引号,则必须在元素前使用反斜杠 (\)。这同样适用于单引号

    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`);

    【讨论】:

      猜你喜欢
      • 2018-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-28
      • 2010-12-01
      • 2011-02-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多