将愚蠢的引号转换为智能引号仅用于文本而非HTML代码

Dumb quotes into smart quotes only for text not HTML code

本文关键字:文本 用于 代码 HTML 转换 智能      更新时间:2023-09-26

我正在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标记的最佳(最有效)方法是什么?谢谢

这里有一种可能的方法(不知道效率,但如果你只处理用户手动输入的字符串,它们可能不会很长,所以这应该无关紧要):

  1. 将字符串分成不重叠的块:HTML标记与其他标记
  2. 仅在非标记中使用"教育引号",不使用标记
  3. 把绳子重新绑起来

如果您正在处理的HTML格式良好(特别是,如果没有"<"浮动),则很容易将其拆分为块:

var html   = '<p style="color:red">some "quotes" in here</p>'
var chunks = html.match(/(<.+?>|[^<]+)/g)
// returns Array: ['<p style="color:red">', 'some "quotes" in here', '</p>']

然后,给定处理替换的clean()函数,您可以说:

cleaned = chunks.map(function(chunk){
  return /</.test(chunk) ? chunk : clean(chunk)
}).join('');

以在<>之间的任何位置应用替换项。