[英]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.