在填充表单输入之前使用 JavaScript 转义字符串

Escaping string using JavaScript before populating form input

我有这段代码,我在其中获取属性值并将其加载到表单中,标题行可能类似于:

欢迎来到美国最有价值的地方

但是使用这个转义函数时,字符串在撇号处被截断,

var headline = escape($(this).attr("data-headline"));

//populate the textbox
$(e.currentTarget).find('input[name="headline"]').val(headline);

我也尝试过使用这里的解决方案:HtmlSpecialChars equivalent in Javascript? 但没有成功。

如何填充我的输入并保留撇号's/quotes?

只需使用

$(this).find('input[name="headline"]').val(this.dataset.headline);

无需任何转义。

但是,请注意 escape 没有切断撇号,而是用 %27 代替它们。如果您当前的代码不适用于标题中的撇号,请确保包含 data-headline 属性的标记已被创建它的任何工具正确转义。

var headline = $(this).attr("data-headline").replace(/'/g, '%27');
//populate the textbox
$(e.currentTarget).find('input[name="headline"]').val(unescape(headline));

如果浏览器兼容性很重要,数据集仅适用于 IE11+ https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset#Browser_compatibility