0

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\">Obama</a></span></div>"
]})

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
  • why not just return the html fragment instead of json. Either that or return the data as json and use a templating plugin to produce the markup. Not sure why your trying to mangle the markup into a json string Commented Jul 26, 2009 at 23:38
  • it's given to me as json. i don't think i have control over the input. Commented Jul 26, 2009 at 23:40

3 Answers 3

4

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

working for me. If there are multiple links inside the html, how do I get the 2nd link, 3rd link, etc... ?
See my update for multiple links - doesn't seem a great way of doing things though... there has to be a better solution. :/
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!
2

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];
}

1 Comment

Firebug says: "invalid regular expression flag a". Did you get it work for you?
0
var link = entireDiv.match(/<a[^>]*>.*<\/a>/);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.