Wednesday, 28 August 2013

Bookmarklet - Verify URL format and extract substring

Bookmarklet - Verify URL format and extract substring

I'm trying to build a bookmarklet that preforms a service client side, but
I'm not really fluent in Javascript. In my code below I want to take the
current page url and first verify that it's a url following a specific
format after the domain, which is...
/photos/[any alphanumeric string]/[any numeric string]
after that 3rd "/" should always be the numeric string that I need to
extract into a var. Also, I can't just start from the end and work
backwards because there will be times that there is another "/" after the
numeric string followed by other things I don't need.
Is indexOf() the right function to verify if the url is the specific
format and how would I write that expression? I've tried several things
related to indexOf() and Regex(), but had no success. I seem to always end
up with an unexpected character or it just doesn't work.
And of course the second part of my question is once I know the url is the
right format, how do I extract the numeric string into a variable?
Thank you for any help!
javascript:(function(){
// Retrieve the url of the current page
var photoUrl = window.location.pathname;
if(photoUrl.indexOf(/photos/[any alphanumeric string]/[any numeric
string]) == true) {
// Extract the numeric substring into a var and do something with it
} else {
// Do something else
}
})();

No comments:

Post a Comment