gpt4 book ai didi

javascript - 问题 "smartening"和链接解析相同的文本

转载 作者:行者123 更新时间:2023-11-30 06:04:58 25 4
gpt4 key购买 nike

我正在使用 jQuery 和一个非常简单的脚本来将引号、撇号和双破折号替换为它们的“智能”对应物:

function smarten(a) {
a = a.replace(/(^|[-\u2014/(\[{"\s])'/g, "$1\u2018"); // opening singles
a = a.replace(/'/g, "\u2019"); // closing singles & apostrophes
a = a.replace(/(^|[-\u2014/(\[{\u2018\s])"/g, "$1\u201c"); // opening doubles
a = a.replace(/"/g, "\u201d"); // closing doubles
a = a.replace(/--/g, "\u2014"); // em-dashes
return a
};

我将其用作对 TwitterJS 的回调,它解析链接并生成如下 block :

<ul>
<li>Here's a link! <a href="http://www.foobar.com">http://www.foobar.com</a></li>
</ul>

问题是如果我这样做:

$('#tweet li').html(smarten($('#tweet li').html()))

它破坏了链接,如果我这样做:

$('#tweet li').html(smarten($('#tweet li').text()))

它完全丢弃了它们。是否有一种智能、稳健的方法来只抓取文本(如果需要,也从 <a> 标记中获取)“聪明”,然后将其放回原处,而不干扰 TwitterJS 的链接解析?

最佳答案

让我们制作一个 jQuery 插件:

jQuery.fn.smarten = (function(){

function smartenNode(node) {
if (node.nodeType === 3) {
node.data = node.data
.replace(/(^|[-\u2014/(\[{"\s])'/g, "$1\u2018")
.replace(/'/g, "\u2019")
.replace(/(^|[-\u2014/(\[{\u2018\s])"/g, "$1\u201c")
.replace(/"/g, "\u201d")
.replace(/--/g, "\u2014");
} else if (node.nodeType === 1) {
if (node = node.firstChild) do {
smartenNode(node);
} while (node = node.nextSibling);
}
}

return function() {
return this.each(function(){
smartenNode(this);
});
};

}());

用法:

$('#tweet li').smarten();

关于javascript - 问题 "smartening"和链接解析相同的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5609823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com