tags:

views:

166

answers:

3

I've almost got this but just need a little push over the edge. I'm parsing a string which contains (potentially) HTML. Here's the code:

function clean(snippet) {
   OBJ = $(snippet);
   txt = OBJ.text();

    if(txt) { 
      parsed = txt;
    } else {
        parsed = snippet;
    }
    return parsed;
}

And here are my test cases:

alert(clean("<div>Randomness</div>")); // Alerts "Randomness"
alert(clean("Randomness"));            // Alerts "Randomness"
alert(clean("<div></div>"));           // Alerts "<div></div>" - should be blank

I can't really figure out how to determine if its just an empty tag that gets passed in vs just plain text and how to deal with it. So I need a test to see if a tag is empty, perhaps. Not sure if that's the best way.

A: 

You're test that txt is not null. try this.

if (txt == '')
David Archer
+1  A: 

You can test if your query returns any objects:

function clean(snippet) {
   OBJ = $(snippet);
   if(OBJ.length == 0)
      return snippet;
   txt = OBJ.text();
   return txt;
}
Kobi
Much better. Works on all test cases, thank you.
Stomped
Pedantically, this is wrong. What if snippet is null. Then again, i've just realised you're still falling in line with @stomped's code. so, @stomped, before you test Obj.length you should test if (obj != null), and its possible that if OBJ is not a string then calling text() will fail. i.e don't forget to add some error handling
David Archer
@David - the function will return `null` in that case - not throw an error. jQuery returns an empty collection (`$(null).length` is `0`). An interesting side effect, however, is `clean('div')` - it enables DOM selections (maybe that was the point though).
Kobi
@kobi, actually, firstly my bad, was trying in a faulted enivironment :-( it doesn't return error, BUT i just tested (properly I hope!) and $(null) == $(document). So OBJ.text() in that case would fall over. I'm not arguing btw to attack your answer, just interested in this now :-)
David Archer
I'm getting 0 for the latest version of jQuery (1.4.2), and 1 for older versions, which is weird.
Kobi
hmm thats interesting, I wonder why they did that
David Archer
A: 

In case you have html you can do something like this:

root = $(snippet);
if (root.text().length > 0) {
  return snippet;
}
if (root.find(":first")) {
   return snippet;
}

This doesn't handle the case the first element inside the div is empty.

kgiannakakis