【问题标题】:input value formation with double quotation marks and single quotes [duplicate]带双引号和单引号的输入值形成[重复]
【发布时间】:2018-04-11 23:17:11
【问题描述】:

我的输入“值”有问题。

$("#printCard").append("<input type='hidden' name='textCard' value='that aren't on the battlefield have flash. ' id='texting'>");

或 JSON:

$("#demo").append("<input type='hidden' name='textCard' value='"+ infoCard.text +"' id='texting'>" );

结果:

<input name="textCard" value="that aren" t="" on="" the="" battlefield="" have="" flash.="" '="" id="texting" type="hidden">

问题是双引号和单引号(不是..)。

这个例子:

The two options I have to save, double quotation marks and single quotes.

谢谢大家

【问题讨论】:

  • 转义值部分中的单引号\'
  • 我创建了一个执行正则表达式的函数,但它不起作用。
  • 你试过 infoCard.text.replace(/'/g, "\\'") 吗?请发布您的尝试和输出
  • 现在...问题是双引号,“.replace()”不起作用。看这个:strInputString = vlr.replace(/'/g, "\\'").replace(/"/g, '\\"');
  • 来自评论:我投票决定保留这个问题,因为它在Escaping single quotes in JavaScript string for JavaScript evaluation 和How do I escape quotes in HTML attribute values 中分别包含两个组件。 @Barmar 对这个问题的 jQuery 回答涵盖了这两个问题。

标签: javascript


【解决方案1】:

如果您不需要支持 IE,请使用 template literals。 TL 是具有更简单语法和额外属性的字符串。以下是 TL 和 SL(String Litral)之间的比较:

语法

SL: 将字符串用双引号或单引号括起来。如果字符串的内容也有引号,则它们应该通过以反斜杠为前缀进行转义:

\" and \'

或使用 HTML entities:

  • &amp;lsquo; 或 &amp;#145;(Left S单QUO标记)

  • &amp;rsquo; 或 &amp;#146;(Right S单QUO标记)?

  • &amp;ldquo; 或 &amp;#147;(Left Double QUO标记)

  • &amp;rdquo; 或 &amp;#148;(Right Double QUO标记)

注意:这些由 HTML 实体表示的特殊引号是弯曲或 智能引号 类型,只能用于纯文本而不是代码。代码中使用的引号是直的,不要混淆它们,因为它们是普遍接受的,它们就像逗号与句点一样不同。

? It's ok to use &amp;rsquo; as an apostrophe - Unicode9.0.0, ch06, pg. 276

TL: 用反引号包裹字符串,也称为重音,在 QWERTY 键盘上,键位于左上角 `。

`template literal`


串联与插值

SL:乱七八糟的单引号、双引号和加号:

var str = '<input id="'+ID+'" class="form-control">';

TL:将变量和表达式包装在:${...}:

var str = `<input id="${ID}" class="form-control">`;

演示

var infoCard = {
  text: "that aren&rsquo;t on the battlefield have flash."
};

$("#printCard0").append(`<input type='hidden' name='textCard' value='that aren&rsquo;t on the battlefield have flash.' id='texting0'>`);


$("#printCard1").append(`<input type='hidden' name='textCard' value='${infoCard.text}' id='texting1'>`);
<main id='core'>

  <figure id='printCard0'></figure>

  <figure id='printCard1'></figure>

</main>





<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

【讨论】:

    【解决方案2】:

    我推荐使用基于对象的方法,这样你就不用担心 HTML 中的特殊字符了。

    $("#printCard").append($("<input>", {
        type: "hidden",
        name: "textCard",
        value: infoCard.text,
        id: "texting"
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-20
      • 2011-06-02
      • 2012-01-06
      • 1970-01-01
      • 2013-06-07
      • 2016-02-15
      • 2016-03-18
      • 1970-01-01
      相关资源
      最近更新 更多