-3

is available var text is a type:

<p>wtjeopitjeltgjelktg <h2> erigjeogjl <h3> <p> etc 

I need count the number of tags <p>

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Fox056
  • 1
  • 2

4 Answers4

3

Parse the string using DOMParser and select the paragraphs using document.querySelectorAll('p') :

var text = `<p>wtjeopitjeltgjelktg <h2> erigjeogjl <h3> <p> etc `;

var parsed = new DOMParser().parseFromString(text, 'text/html');

const paragraphs = parsed.querySelectorAll('p');

console.log(paragraphs.length);
Taki
  • 17,320
  • 4
  • 26
  • 47
1

you can simple count

using this

var temp = "<p>wtjeopitjeltgjelktg <h2> erigjeogjl <h3> <p> etc ";
var count = (temp.match(/<p>/g) || []).length;
console.log(count);
1

Using a regualr expression can produce the wrong number of elements. Best way would be to convert it to HTML and use DOM.

var str = '<p>hello</p><p class="foo">world</p><p style="color: red">apple</p>'

var div = document.createElement("div")
div.innerHTML = str;
var count = div.getElementsByTagName("p").length
console.log(count)

A regular expression is a bad idea, but a basic one would be

var str = '<p>hello</p><p class="foo">world</p><p style="color: red">apple</p><param>aaaa</param>'
var matches = str.match(/<p(\s[^>]*)?>/g)
var count = matches ? matches.length : 0
console.log(count)
epascarello
  • 204,599
  • 20
  • 195
  • 236
-2

If in frontend You can achieve with Jquery $('p').length.

If you are looking for a backend function you can use Cheerio

megna
  • 11
  • 3