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

标签 javascript

这是我的字符串。它包含一些 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/

相关文章:

javascript - 如何在 Javascript/Typescript 中使用 import 和 require?

javascript - JS : Adding and removing elements in nested array, 代表表数据

javascript - 如何正确设计后端结构来处理消息服务?

javascript - 删除元素时数组返回未定义

javascript - Node.js Mongoskin 集合迭代 > Jade

javascript - 赋值作为参数

javascript - Javascript 有包含函数吗?

javascript - 我使用 bootstrap.js 还是所有 14 个单独的 .js 文件有什么关系吗?尝试建立词缀行为

javascript - 在没有类似 AJAX 的 PostBack 的情况下更改复选框背景颜色

javascript - 如何计算射击子弹以击中移动目标的 Angular ?