user4621642
user4621642

Reputation:

Extracting data from an HTML code

I have this piece of HTML code as a string stored in a variable.

<p style="text-align: center;">
    <span style="font-size: small;font-family: comic sans ms', sans-serif;">
        <strong>
            word1&nbsp;
            <span style="line-height: 1.5;">
                word2&nbsp;
            </span>
            <span style="line-height: 1.5;">
                word3&nbsp;
            </span>
            <span style="line-height:1.5;"></span>
        </strong>
    </span>
</p>

I want only to extract word1&nbsp;, word2&nbsp; and word3&nbsp;. How can I do it in an easiest and time efficient way?

I was thinking the character > that was not preceded immediately by < can be a index where I can start extracting my data.

Upvotes: 1

Views: 96

Answers (5)

memo
memo

Reputation: 273

Since you used regex tag I will post a solution with regex.

var re = /\w+&nbsp;/g;
var results = html.match(re);

Then you can access the results from "results" array.

Upvotes: 1

madalinivascu
madalinivascu

Reputation: 32354

Try something like this:

var html = '<p style="text-align: center;">
    <span style="font-size: small;font-family: comic sans ms, sans-serif;">
        <strong>
            alyssa&nbsp;
            <span style="line-height: 1.5;">
                enganio&nbsp;
            </span>
            <span style="line-height: 1.5;">
                gono&nbsp;
            </span>
            <span style="line-height:1.5;"></span>
        </strong>
    </span>
</p>';
    var values = $(html).find('p strong').text().split(' ');

or

var v =[];
v.push($(html).find('p strong').clone().find('span').remove().end().text());
$(html).find('p strong span').each(function(i,val) {
if($.trim($(val).text()).length>0)
v.push($(val).text())
});
console.log(v);

Upvotes: 1

amirpaia
amirpaia

Reputation: 376

I think you want fetch text of tag without text of children.

So just see this thread

This code:

 console.log($("strong").clone().children().remove().end().text());

And to changing a string to jQuery object see this thread

This code:

var element = $('<div id="a1"></div><div id="a3"></div>');

Upvotes: 0

Pawan Kashyap
Pawan Kashyap

Reputation: 146

Using jQuery you can fetch easily

lets try this one:-

$('p').text();

it will return the combined text contents of each element in the set of matched elements, including their descendants, or also used to set the text contents of the matched elements.

Upvotes: 1

Dhara Parmar
Dhara Parmar

Reputation: 8101

Just use this, it will return you all text inside p tag - "alyssa&nbsp; , enganio&nbsp; , gono&nbsp;":

alert($("p").text());

Upvotes: 0

Related Questions