[英]Javascript: How to get array of strings of text within p tags
可以说我里面有很多p标签的字符串...
var myString = "<p>Some text.</p><p>Some more. Some more text.</p><p>And even some more text.</p>";
..如何获取数组,数组中的每个项目都是p标记中的一串文本:
[
"Some text.",
"Some more. Some more text.",
"And even some more text."
]
我想的一种方法是摆脱p标签...
var stringWithOutTags = myString.replace(/(<p>|<\/p>)/g, " ");
..然后使用.split()找出每个句子。 但我真的不想弄出每个句子,只想在p标签中加上文字
var stringAsArray = stringWithOutTags.split(".");
如果要在浏览器上执行代码,则可以将字符串解析为HTML而不是使用正则表达式:
var el = document.createElement('div');
el.innerHTML = myString;
var texts = [].map.call(el.querySelectorAll('p'), function(p) {
return p.textContent;
});
您可以从字符串中省略<p>标记,而仅使用结束</ p>标记进行拆分,以获得所需的结果。
myString.replace('<p>', '').split('</p>');
注意:仅当您确定可以信任输入字符串(即不是用户输入)时,才使用此方法!
var myString = "<p>Some text.</p><p>Some more. Some more text.</p><p>And even some more text.</p>";
// Create a "div" element
var div = document.createElement("div");
// Get browser to parse string, and set the parsed HTML elements as
// the contents of the div element
div.innerHTML = myString;
// Loop over the child elements of the div, and return an array of
// the textual content the elements. If you wish to preserve tags
// inside the <p> elements, replace .textContent with .innerHTML
var arrayOfStrings = Array.prototype.map.call(div.childNodes, function (pTag) {
return pTag.textContent;
});
更换后为何不拆分:
var a = "<p>Some text.</p><p>Some more. Some more text.</p><p>And even some more text.</p>";
var b = a.replace(/(<p>|<\/p>)/g, " ").split(' ');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.