views:

366

answers:

3

Hi, I want to get a subset of a string in Javascript. Currently, I only know how to store the entire string:

I have this as a JSON variable with a callback to foo:

foo({"results":[
"<div id=\"following\"><span><a href=\"http://twitter.com/barackobama\"&gt;Obama&lt;/a&gt;&lt;/span&gt;&lt;/div&gt;"
]})

And this is my callback function:

function foo(o){
  var entireDiv = o.results[0];
}

How do I store just the "< a href = ... > ... < / a> " tag as a string in Javascript?

+2  A: 

You can use a regular expression to find the anchor tag:

function foo(o){
  var entireDiv = o.results[0];
  var link = /<a.+?\/a>/.exec(entireDiv)[0];
}
Guffa
Firebug says: "invalid regular expression flag a". Did you get it work for you?
chris
ok, it needs the backslash in front of the second a
chris
Right... I usually use regular expressions in C#, not Javascript...
Guffa
A: 
var link = entireDiv.match(/<a[^>]*>.*<\/a>/);
+2  A: 

With jQuery, you can parse in a piece of HTML as the second argument.

So, to update your foo function:

$j = jQuery.noConflict();

function foo(o)
{
    var JustTheLink = $j( 'a' , o.results[0] ).parent().html();
}


Update:
With multiple links to handle, you can do this:

function foo(o)
{
    $j('a',o.results[0]).each(handleSrc);
}

function handleSrc()
{
    console.log(this); // tag
    console.log($j(this).html()); // contents
}
Peter Boughton
working for me. If there are multiple links inside the html, how do I get the 2nd link, 3rd link, etc... ?
chris
See my update for multiple links - doesn't seem a great way of doing things though... there has to be a better solution. :/
Peter Boughton
yea. since my input is relatively fixed, I know exactly how many links I have, so I figured out I should specify the links using a css selector. Works in my case. Thanks!
chris