user2426701
user2426701

Reputation:

Get a specific string from Url

I know it may sound as a common question, but I have different variables here: I have an Url like this one:

https://www.facebook.com/events/546604752058417/?suggestsessionid=791e61ca005570613fa552635bc794a5

Now I need to get the number 546604752058417. So logically I should get all what is after events/ but all what is after the first slash after 546604752058417

Now the problem is that the Url may or not start with http, https, www, etc..

I am a little lost and new to Javascript.

What's the simple way to do it?

I have a function that check if the Url is valid and it is from Facebook, but I don't know now how to get that 546604752058417.

Obviously this is only a sample. The function should be able to work with any event id.

    function fbProcessSearch() {
        var search_url = $("#search_fb_url").val();

        if(isFbUrl(search_url)) {
            $("#search_fb_event").validationEngine("hide");
         // gets the event id from the Url and passes it to the below function.
            fbProcess(eid);
        }else{
            $("#search_fb_event").validationEngine("showPrompt", "Please enter the Facebook event Url", "load", "topLeft", true);
    }
 }

    function isFbUrl(url) {
        var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
        return regexp.test(url) && url.indexOf("facebook.com") > -1;
}

Upvotes: 0

Views: 69

Answers (3)

mahdilamb
mahdilamb

Reputation: 535

if you know how the url is going to look and can confirm it's facebook. then .split("events/")[1].split("/")[0] to get the code between /events/######/

Upvotes: 1

t.c
t.c

Reputation: 1257

you can start by "spliting" your url with "/"

var search_url = $("#search_fb_url").val().split("/");

and then you take the field after the one containing "events" ....

Upvotes: 0

Dogbert
Dogbert

Reputation: 222168

Use .match with this regexp: /events\/(.*?)\//

"https://www.facebook.com/events/546604752058417/?suggestsessionid=791e61ca005570613fa552635bc794a5".match(/events\/(.*?)\//)[1]
=> "546604752058417"

Explanation:

events\/ -> Match "/events/" literally
(.*?)\/  -> match anything until first "/" and also capture it

Upvotes: 2

Related Questions