防止由于“引号”符号而导致串联时出错的常用方法

Common approach to prevent error during concatenation because of a `quote` symbol

本文关键字:出错 方法 常用 引号 符号      更新时间:2023-09-26

我正在把一个html标签组装成这样的字符串:

var tag = '<div some-attribute="' + attributeValue + '">';

问题是,如果attributeValue包含引号",则会在组装标签时出现错误。避免这种情况的常见方法是什么?我正在寻找一个解决方案,考虑到所有可能的报价符号的变化。

您可以使用encodeURIComponent全局方法,该方法将从字符串中转义特殊字符;

你只需要在用decodeURIComponent 访问它时对它进行解码

var attributeValue = '"some'
var tag = '<div data-some-attribute="' + encodeURIComponent(attributeValue) + '">';
tag // "<div some-attribute="%22some">"

访问它

var attribute = decodeURIComponent(div.getAttribute('data-some-attribute'));
attribute // "some

我建议您在Javascript中使用"双引号,并在字符串中包含html可以理解的'单引号

您还可以通过在字符串中的引号之前放置'来转义它们,而不是分隔符的一部分。

您的示例如下:

var tag = "<div some-attribute='"" + attributeValue + "'">";

最佳解决方案是动态创建一个对象,将属性添加到其中。

var tag = document.createElement('div'); // this creates a DOM div element
tag.setAttribute("some-attribute", attributeValue); // this changes the some-attribue to the value (could use with class)
containerElement.appendChild(tag); // this appends the newly created element as html in the container

我还建议您查看另一个问题,并获得关于如何使用Javascript创建和附加元素的更完整的回答。

这个答案解释了如果属性值用双引号括起来,那么一个属性值中只有两个字符无效:

如果您的属性值有引号(以双引号开始和结束"),则除双引号和与号之外的任何字符都是允许,必须引用为&quot;&amp;

所以我只替换了这两个字符,然后将属性值视为安全的:

var safe = attributeValue.replace("&", '&amp;').replace('"', '&quot;');
var tag = '<div some-attribute="' + safe + '">';