Javascript:如何获取 p 标签内的文本字符串数组

问题描述 投票:0回答:5

假设我有一个带有很多 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(".");
javascript arrays string
5个回答
3
投票

如果您在浏览器上执行代码,您可以将字符串解析为 HTML,而不是使用正则表达式:

var el = document.createElement('div');
el.innerHTML = myString;
var texts = [].map.call(el.querySelectorAll('p'), function(p) {
   return p.textContent;
});

3
投票

您可以从字符串中省略

标签,并使用结束

标签进行拆分,以获得所需的结果。

myString.replace('<p>', '').split('</p>');

1
投票

更换后为何不拆分:

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

https://jsbin.com/wopute/1/edit?js,控制台


1
投票

注意:仅当您确定可以信任输入字符串(即不是用户输入)时,才请使用此方法!

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

0
投票

返回一个包含每个字符串的字符串数组 类似 HTML 的

<p></p>
标签中的原始字符串。

const names = ["alice", "bob", "charlie", "danielle"]

const wrapped = names.map( (name) => {
    return `<p>${name}</p>`
} )

console.log(wrapped)
© www.soinside.com 2019 - 2024. All rights reserved.