目前,我正在处理被分成 float 列的文本,以将其显示在 magazine-like
中。方式。
我在 previous question 中问过如何split
将文本变成句子,它就像一个魅力:
sentences = text.replace(/\.\s+/g,'.|').replace(/\?\s/g,'?|').replace(/\!\s/g,'!|').split("|");
现在我想更进一步,将其分解为单词。但我确实也有一些元素在里面,不应该被分割。就像副标题一样。
示例文本如下:
A wonderful serenity has taken possession of my entire soul. <strong>This is a subheadline</strong><br><br>I am alone, and feel the charm of existence in this spot.
我想要的结果如下所示:
Array [
"A",
"wonderful",
"serenity",
"has",
"taken",
"possession",
"of",
"my",
"entire",
"soul.",
"<strong>This is a subheadline</strong>",
"<br>",
"<br>",
"I",
"am",
"alone,",
"and",
"feel",
"the",
"charm",
"of",
"existence",
"in",
"this",
"spot."
]
当我分割所有空格时,我确实得到了单词,但是 "<br>"
不会添加为新的数组条目。我也不想拆分副标题和标记。
我想这样做的原因是,我将一个又一个的序列添加到p标签中,当高度大于周围元素时,我删除最后添加的序列并创建一个新的 float p标签。当我将其拆分成句子时,我发现拆分效果不足以确保良好的阅读流程。
我试图实现的一个例子你能看到here
如果您需要任何进一步的信息,我很乐意为您提供。
提前致谢,
托比亚斯
编辑
该字符串将来可能包含更多 html 标签。有没有办法不碰这些标签之间的任何内容?
编辑2
我创建了一个jsfiddle:http://jsfiddle.net/m9r9q/1/
编辑3
删除所有带有封装文本的 html 标签并用占位符替换它是一个好主意吗?然后将字符串分割成单词并在到达占位符时添加未触及的 html 标签?提取所有 html 标签的正则表达式是什么?
最佳答案
Although i want to try to extract the html parts and add them afterwards untouched
忘记它和我之前的帖子。 我刚刚想到,使用内置的浏览器引擎来操作 html 代码会更好。
你可以使用这个:
var text = 'A wonderful serenity has taken possession of my entire soul. <strong>This is a subheadline</strong><br><br>I am alone, and feel the charm of existence in this spot.';
var elem = document.createElement('div');
elem.innerHTML = text;
var array = [];
for(var i = 0, childs = elem.childNodes; i < childs.length; i ++) {
if (childs[i].nodeType === 3 /* document.TEXT_NODE */) {
array = array.concat(childs[i].nodeValue.trim().split(/\s+/));
} else {
array.push(childs[i].outerHTML);
}
}
这次它确实支持嵌套标签,而且它支持所有可能的语法,没有针对不可关闭标签的硬编码异常:)
关于javascript - 在javascript中将字符串拆分为单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18927223/