gpt4 book ai didi

javascript - 将包含 HTML 的字符串转换为句子,并使用 Javascript 保留分隔符

转载 作者:搜寻专家 更新时间:2023-11-01 04:37:40 25 4
gpt4 key购买 nike

这是我的字符串。它包含一些 HTML:

First sentence. Here is a <a href="http://google.com">Google</a> link in the second sentence! The third sentence might contain an image like this <img src="http://link.to.image.com/hello.png" /> and ends with !? The last sentence looks like <b>this</b>??

我想将字符串拆分为句子(数组),保留 HTML 以及分隔符。像这样:

[0] = First sentence.
[1] = Here is a <a href="http://google.com">Google</a> link in the second sentence!
[2] = The third sentence might contain an image like this <img src="http://link.to.image.com/hello.png" /> and ends with !?
[3] = The last sentence looks like <b>this</b>??

有人可以建议我一个方法吗?可能正在使用正则表达式和匹配?

这非常接近我所追求的,但不是真正的 HTML 位: JavaScript Split Regular Expression keep the delimiter

最佳答案

最简单的部分是解析;您可以通过在字符串周围包装一个元素来轻松地做到这一点。拆分句子有点复杂;这是我第一次尝试:

var s = 'First sentence. Here is a <a href="http://google.com">Google.</a> link in the second sentence! The third sentence might contain an image like this <img src="http://link.to.image.com/hello.png" /> and ends with !? The last sentence looks like <b>this</b>??';

var wrapper = document.createElement('div');
wrapper.innerHTML = s;

var sentences = [],
buffer = [],
re = /[^.!?]+[.!?]+/g;

[].forEach.call(wrapper.childNodes, function(node) {
if (node.nodeType == 1) {
buffer.push(node.outerHTML); // save html
} else if (node.nodeType == 3) {
var str = node.textContent; // shift sentences
while ((match = re.exec(str)) !== null) {
sentences.push(buffer.join('') + match);
buffer = [];
str = str.substr(re.lastIndex + 1);
re.lastIndex = 0; // reset regexp
}
buffer.push(str);
}
});

if (buffer.length) {
sentences.push(buffer.join(''));
}

console.log(sentences);

Demo

每个节点,无论是元素还是未完成的句子,都会被添加到缓冲区中,直到找到完整的句子;然后将其添加到结果数组中。

关于javascript - 将包含 HTML 的字符串转换为句子,并使用 Javascript 保留分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16374843/

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