Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dividing a string in 2 parts and placing each part in a different new string

I have a string (resultString) that contains long html codes. These codes are grouped in 2 main DIVs, window and Popup.

resultString = "<div id=\"window\">window content --- long html codes</div><div id=\"PopUp\">Popup content --- long html codes</div>"

Now I want to retrieve the html content of window and popup DIVs separately and place them in 2 different strings (stringWindow and stringPopup).

stringWindow = "<div id=\"window\">window content --- long html codes</div>";
stringPopup = "<div id=\"PopUp\">Popup content --- long html codes</div>";

Is there any simple way to do so in jQuery/javascript? The stringWindow is constructed in an Ajax json webmethod function. Any help is well appreciated! Thanks in advance.

like image 927
Gloria Avatar asked Aug 11 '15 06:08

Gloria


3 Answers

You can use filter() and outerHTML

  1. Using filter you can filter element with certain selector
  2. Now you can use outerHTML for getting html content

var resultString = "<div id=\"window\">window content --- long html codes</div><div id=\"PopUp\">Popup content --- long html codes</div>",
  stringWindow, stringPopup;

stringWindow = $(resultString).filter('#window')[0].outerHTML;
stringPopup = $(resultString).filter('#PopUp')[0].outerHTML;

console.log(stringPopup, stringPopup);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
like image 50
Pranav C Balan Avatar answered Sep 22 '22 04:09

Pranav C Balan


Trivial in jQuery:

var resultString = "<div id=\"window\">window content --- long html codes</div><div id=\"PopUp\">Popup content --- long html codes</div>"

var $doc = $("<div>" + resultString + "</div>");
var stringWindow = $doc.find('#window').text();
var stringPopup = $doc.find('#PopUp').text();
console.log("window", stringWindow);
console.log("popup", stringPopup);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- results pane console output; see http://meta.stackexchange.com/a/242491 -->
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

Not much harder in plain JS.

If by "Just the content" you don't mean "text" but markup inside the div, then replace text() with html().

EDIT: made into executable snippet.

like image 33
Amadan Avatar answered Sep 21 '22 04:09

Amadan


A version that doesn't use jQuery, doesn't assume it is in the document or can be put into the document but still interprets it as HTML -

var domParser = new DOMParser(),
    doc = domParser.parseFromString(resultString, "text/html"),
    content = ["window", "PopUp"].map(function(id) {
        return doc.querySelector("#" + id).innerHTML;
    }),
    stringWindow = content[0],
    stringPopup = content[1];
like image 34
George Simms Avatar answered Sep 19 '22 04:09

George Simms