Regular expressions to add classes to html tags

673 Views Asked by At

I am working on a reactjs project and have basic html coming through via json. I need to go back over the markup and append bootstrap classes to it so its styled properly on the page.

the current function

  const markupFormatting = (html) => {
    html = html.replace(/<p/g, '<p class="paragraph-margin-bottom-10 text--font-size-14 paragraph--justified"')
    html = html.replace(/<a/g, '<a class="text--font-size-14 hyperlink-primary"')
    return html
  }

http://jsfiddle.net/0ht35rpb/64/

Is there a cleaner way of doing this?

2

There are 2 best solutions below

9
kraf On

You could use jQuery to parse the HTML and add the classes

const $html = $(html);
$html.find('p').addClass('paragraph-margin-bottom-10 text--font-size-14 paragraph--justified');
$html.find('a').addClass('text--font-size-14 hyperlink-primary');
return $html.html();

This protects you from a few edge cases, e.g. adding a duplicate class property. This works on the server side as well with the cheerio library.

PS: There is this jewel about using RegEx to work with HTML: RegEx match open tags except XHTML self-contained tags.

0
Sanchit Goel On

You can use it in this way:

  var html1 = '<p>some test with a <a href="text">link</a></p><p>another paragraph with a <a href="test2">link</a></p>';

  function markupFormatting(html1){
    var e = document.createElement('div');
    e.innerHTML = html1;

    e.querySelectorAll('a').forEach(function(obj,i){obj.setAttribute("class", "abc")});

    return e;
  }

  console.log(markupFormatting(html1))