-4

What can be the regex to parse an html and modify the html such that the outermost 'div' having our custom class?

for example: my input html can be like:

<p><div>sample text<div>this is another div</div></div></p>

I want a result like

<p><div class="myclass">sample text<div>this is another div</div></div></p>
Stanly
  • 663
  • 1
  • 9
  • 26

1 Answers1

1

Assuming you're manipulating just a raw string that happens to contain html-like syntax, you'll probably want something like this:

var htmlString = '<p><div>sample text<div>this is another div</div></div></p>'

var className = 'test';
var firstDivIndex = htmlString.indexOf('<div') + 4;
var manipulatedHtml = htmlString.substring(0, firstDivIndex) + ' class="' + className + '"' + htmlString.substring(firstDivIndex);

console.log(manipulatedHtml)

This isn't using regex, just simple string manipulation, I'll throw together a codepen for you if you'd like as well

EDIT: Alright, here's an example with the desired functionality, open up your console to see the result - http://codepen.io/csavage1994/pen/PpRNPa

Colton
  • 218
  • 1
  • 2
  • 10