Регулярное выражение, чтобы убрать весь тег p со строки и поместить его в массив - PullRequest
1 голос
/ 25 апреля 2019

У меня есть строковый ответ API, в котором смешаны все данные. Я хочу написать регулярное выражение для целевых тегов p, извлечь их содержимое и поместить в массив.

Пример:

const string = "Plain text <p>First para content</p> Another plain text<p>Second para content</p> Another random text and other stuff <p>Third Para content</p>"

Желаемый результат может быть:

const arrayOfParagrahs = ['First para content', 'Second para content', 'Third Para content']

Ответы [ 3 ]

1 голос
/ 25 апреля 2019

Используйте это регулярное выражение /<p>(.*?)<\/p>/g, как в следующем фрагменте:

let str = "Plain text <p>First para content</p> Another plain text<p>Second para content</p> Another random text and other stuff <p>Third Para content</p>"

var result = str.match(/<p>(.*?)<\/p>/g).map(val => {
   return val.replace(/<\/?p>/g, '')
})

console.log(result)
0 голосов
/ 25 апреля 2019

Попробуйте

string.match(/<p>.*?<\/p>/g).map(x=>x.slice(3,-4))

const string = "Plain text <p>First para content</p> Another plain text<p>Second para content</p> Another random text and other stuff <p>Third Para content</p>"

let arrayOfParagrahs= string.match(/<p>.*?<\/p>/g).map(x=>x.slice(3,-4))

console.log(arrayOfParagrahs);
0 голосов
/ 25 апреля 2019

Другое решение (без регулярных выражений) заключается в использовании обычных селекторов dom в javascript.

Вы можете создать элемент dom с вашей html-строкой как innerHTML.

После этого вы можете использовать обычные селекторы JavaScript, такие как getElementsByTagName('p') или querySelectorAll('p').

const str = "Plain text <p>First para content</p> Another plain text<p>Second para content</p> Another random text and other stuff <p>Third Para content</p>";

const virtEl = document.createElement('div');
virtEl.innerHTML = str;

const pArray = Array.from(virtEl.getElementsByTagName('p'));
const plessArray = pArray.map(e => e.textContent)

console.log(plessArray)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...