【发布时间】:2025-12-27 10:00:11
【问题描述】:
我正在将 contenteditable 中的哑引号转换为智能引号,但问题是它也会在 HTML 元素中替换它们,例如:
<a href=“something” title=“something”
从而使它们无效。我只想为用户的文本做这件事。这是问题所在。我必须保留原始格式元素,所以我不能这样做:
clean($('#something_container').text());
这将在返回时删除所有 HTML 元素(格式)。这是我的代码:
content = clean($('#post_content').html());
$('#post_content').html(content);
// replaces ", ', --, <div> with <p>
function clean(html) {
html = html.replace(/'\b/g, "\u2018") // opening singles
.replace(/\b'/g, "\u2019") // closing singles
.replace(/"\b/g, "\u201c") // opening doubles
.replace(/\b"/g, "\u201d") // closing doubles
.replace(/--/g, "\u2014") // em-dashes
.replace(/<div>/g, "<p>") //<div> to <p>
.replace(/<\/div>/g, "</p>"); //</div> to </p>
return html;
};
什么是仅在用户文本中替换哑引号并跳过像<img src="" />这样的HTML标签的最佳(最有效)方法?谢谢!
【问题讨论】:
-
请注意,替换
<div>不会捕获带有属性的 DIV,例如<div class="...">。另外,最后一个replace应该是</p>。 -
@fanaugen 哎呀,修复它。我不关心类,只关心某些浏览器在更改格式时插入的(例如从
- 到
)
标签: javascript html replace quotes