5

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

4

1 回答 1

1

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

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);

演示

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

于 2013-05-04T14:36:04.937 回答