Xtian
Xtian

Reputation: 3587

get last part of this URL

I am grabbing this strange URL out of an Object in a Twitter button:

http://platform.twitter.com/widgets/tweet_button.1329950604.html#_=1330013339435&count=none&hashtags=allstar&id=twitter-widget-10&lang=en&original_referer=http%3A%2F%2Fwww.nba.com%2Fpulse%2Fallstar%2F2012%2Findex.html&related=%40nba&size=m&text=Sprite%20Slam%20Dunk%20Contest%20is%20trending%20on%20NBA%20All-Star%20Pulse%20&url=http%3A%2F%2Fwww.nba.com%2Fpulse%2Fallstar%2F2012%2Ftopics%2Fspriteslamdunk.html

I need to get the last part before the '.html' which in the example above is:spriteslamdunk

this seems to appear after %2Ftopics%2F

not sure how to extract that with jQuery?

[EDIT] Looks like I have to do it with Regex? Haven't done much with Regex in this regard??

Upvotes: 1

Views: 751

Answers (3)

steveyang
steveyang

Reputation: 9288

You want to retrieve the string before .html and after the last appearance of %2F.

You could use the regular expression /%2F([^%]+?)(\.html$)/. \.html$ matches the string before last appearance; ([^%]+?) part matches the shortest string which doesn't include % and before .html which is what you want to retrieve; %2F excludes this string in matches.

var str = "http://platform.twitter.com/widgets/tweet_button.1329950604.html#_=1330013339435&count=none&hashtags=allstar&id=twitter-widget-10&lang=en&original_referer=http%3A%2F%2Fwww.nba.com%2Fpulse%2Fallstar%2F2012%2Findex.html&related=%40nba&size=m&text=Sprite%20Slam%20Dunk%20Contest%20is%20trending%20on%20NBA%20All-Star%20Pulse%20&url=http%3A%2F%2Fwww.nba.com%2Fpulse%2Fallstar%2F2012%2Ftopics%2Fspriteslamdunk.html"

var matches = str.match(/%2F([^%]+?)(\.html$)/)

matches
// => ["%2Fspriteslamdunk.html", "spriteslamdunk", ".html"]

matches[1] // What you want.

Upvotes: 0

DaveS
DaveS

Reputation: 3294

var answer = url.substring(url.lastIndexOf("%2F") + 3).replace(".html","")

Upvotes: 0

Eric Yin
Eric Yin

Reputation: 8973

I guess you might have to use regex "(\w+)\.html$"

Upvotes: 3

Related Questions