Question

I have the following string :

var str='
                <span class="productName">Basa fillets</span><br>
                Brand: 
                <span class="brandName">COMPLIMENTS</span><br>
                400 <abbr title="Gram" lang="en">gr</abbr>
            '

I need to get the '400' (could be a word,or even a sentence). What I have so far is :

d = str.replace(/<br>/g,'').replace(/<.*<\/.*>/g,'').replace(/\n/g,'').replace(/ */g,'').replace(/brand:/i,'');

It works but... well, I'm sure I can do better. i have plenty of similar queued replace in my code, and I'd like to know how to improve that so i'm more looking for a general answer than a particular solution.

Thanks!

Was it helpful?

Solution

Instead of using string tools/regex on this, you can use DOM methods on it (it is HTML).

First you make a "fake" div and add the HTML to it.

var str="\
                <span class=\"productName\">Basa fillets</span><br>\
                Brand: \
                <span class=\"brandName\">COMPLIMENTS</span><br>\
                400 <abbr title=\"Gram\" lang=\"en\">gr</abbr>\
            ";

var fakeDiv = document.createElement('div');
fakeDiv.innerHTML = str;

Then just use normal DOM traversal methods to get the node you need. There are many ways to get to the element, depending on your HTML.

var brandName = fakeDiv.getElementsByClassName('brandName');

var textNode = brandName[0].nextSibling.nextSibling;

console.log(textNode.nodeValue.trim());

DEMO: http://jsfiddle.net/aqpgV/

Or, you can start from the <abbr> element and work backwards.

var gram = fakeDiv.getElementsByTagName('abbr');

var textNode = gram[0].previousSibling;

console.log(textNode.nodeValue.trim());

DEMO: http://jsfiddle.net/aqpgV/1/

However you traverse it is up to you :-)

OTHER TIPS

Regex

class="brandName">[^<]+</span><br>[^\w]+([^<]+) <abbr title=

Regular expression visualization

Debuggex Demo

Notes: Group 1 will contain the item you want.

If you wanted to use regex, you could do something like this.

    var str="\
            <span class=\"productName\">Basa fillets</span><br>\
            Brand: \
            <span class=\"brandName\">COMPLIMENTS</span><br>\
            400 <abbr title=\"Gram\" lang=\"en\">gr</abbr>\
        ";

    var myRegexp = /COMPLIMENTS<\/span><br>\W(.*?) <abbr /g;
    var match = myRegexp.exec(str);
    alert(match[1]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top