1

I am editing large html file and it is necessary to insert <span id="%d"></span> (where %d is the number of match) into the <p></p> tags.

Sample Input:

<p>stack</p>
<p>overflow</p>

Desired Output:

<p><span class="class" id="f=1">stack</p>
<p><span class="class" id="f=2">overflow</p>

To match the <p></p> I use the following regular expression to match results: <p>(.*?)<\/p>

Afterwards, matches are substituted with: <p><span class="class" id="f=???">$1</span></p>

Is it available reference to the number of match from pattern? ("f=???")

Neil Galiaskarov
  • 5,015
  • 2
  • 27
  • 46

2 Answers2

2

RegEx can't count matches, so you'd have to do that part in JavaScript.

var input = "<p>stack</p>\n<p>overflow</p>"

const regex = /<p>(.*?)<\/p>/g;

var count = 0;
var result = input.replace(regex, function(match, contents) {
    ++count;
    return '<p><span class="class" id="f=' + count + '">' + contents + '</span></p>';
});

console.log(result);

console.log(result) would yield:

<p><span class="class" id="f=1">stack</span></p>
<p><span class="class" id="f=2">overflow</span></p>
vallentin
  • 23,478
  • 6
  • 59
  • 81
1

It's not recommended to parse HTML using regex :

RegEx match open tags except XHTML self-contained tags

Using regular expressions to parse HTML: why not?


Instead, generate a DOM element with the content and update the p tags.

var str = `<p>stack</p>
<p>overflow</p>`;

// generate a temporary div element
var temp = document.createElement('div');
// set html content
temp.innerHTML = str;

// get all p tags and convert into array
// for older browser use [].slice.call(.....)
Array.from(temp.querySelectorAll('p'))
  // iterate over the elements
  .forEach(function(ele, i) {
    //  update the content
    ele.innerHTML = '<span class="class" id="f=' + (i + 1) + '">' + ele.innerHTML + '</span>';
  });

// get the html content
console.log(temp.innerHTML);
Community
  • 1
  • 1
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188