Manipulate html-string variable with javascript

I need to manipulate a string variable with JavaScript that has some html content. I want to find some elements, modify them and wrap these elements with another div container.

How can I get this:

var myArr = ['Foo', 'Bar'];
var contenthtml = "<p>Foo</p>
  <p>Lorem ipsum dolor sit amet</p>
  <p>Lorem <b>ipsum</b> dolor sit amet</p>
  <p>Lorem ipsum dolor sit amet</p>
  <p>Bar</p>
  <p>Lorem ipsum dolor sit amet</p>";

:

contenthtml = "<div class='foo'><h1>Foo</h1>
  <p>Lorem ipsum dolor sit amet</p>
  <p>Lorem <b>ipsum</b> dolor sit amet</p>
  <p>Lorem ipsum dolor sit amet</p></div>
  <div class='bar'><h1>Bar</h1>
  <p>Lorem ipsum dolor sit amet</p></div>";
+3
source share
3 answers

I used some DOMs to solve this problem. For those who prefer a DOM solution over RegExp:

Add items to a variable instead of a temporary DOM

+1
source

You can use regex (similar to my other answer at fooobar.com/questions/2109895 / ... ):

var keywordsRegEx = keywords.map(function(x){return x.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');}).join('|');
var result = str.replace(new RegExp('<p>(' + keywordsRegEx + ')</p>\r\n((?:[ \t]*<p>(?:(?!' + keywordsRegEx + ').)*</p>(?:\r\n)?)*)', 'mgi'), '<div><h1 class="$1">$1</h1>\r\n$2</div>\r\n');

For a complete example, see http://jsfiddle.net/ncu43/1/ .

, <p>, , </p>, ( ) .

+1

It would be a little easier with direct DOM replacement / packaging (I actually wrote such a solution, but rewrote it when I saw your comment about the need to enter a string), but here is a solution that uses only a string as input:

var myArr = ['Foo', 'Bar'];
var contenthtml = '<p>Foo</p>\n'
    + '<p>Lorem ipsum dolor sit amet</p>\n'
    + '<p>Lorem <b>ipsum</b> dolor sit amet</p>\n'
    + '<p>Lorem ipsum dolor sit amet</p>\n'
    + '<p>Bar</p>\n'
    + '<p>Lorem ipsum dolor sit amet</p>';
var elements = $.parseHTML(contenthtml);
var tmp = '';
$.each(elements, function(index, element) {
    $.each(myArr, function(i, e) {
        if (element.innerHTML == e) {
            elements[index] = $('<h1>' + e + '</h1>').get(0);
            return;
        }
    });
    if (elements[index].outerHTML) {
        tmp += elements[index].outerHTML + '\n';
    }
});
contenthtml = '<div class="foo">' + tmp + '</div>';
console.log(contenthtml);

jsfiddle

0
source

All Articles