Reputation: 76
Trying to write a javascript bookmarklet to jump from a front end link into a CMS edit page link.
So take a url like this
http://www.example.com/events/13097/article
and make a url like this
http://www.example.com/admin/edit.php?class=events&id=13097
I think I need to use regex to grab the class and id and then wrap it into a javascript function- but I'm a absolute beginner and wondering if someone can get me started?
Upvotes: 4
Views: 2672
Reputation: 18022
You don't need regex, Try this:
var url = ""+window.location;
var urlparts = url.split('/');
window.location = "http://www.example.com/admin/edit.php?class="+urlparts[3]+"&id="+urlparts[4];
splits the class and the id from the URL and repeats them in the redirect.
the first line casts the window.location
to a string you could also use String(window.location)
to do this, but that's more verbose.
to get the domain too, you can use:
"http://"+urlparts[2]+"/admin/edit.php?class="+urlparts[3]+"&id="+urlparts[4]
EDIT: Actually, you can get the urlparts
with window.location.href.split('/')
or to emulate the original code window.location.toString().split('/')
other items of interest in the window.location
object (examples from this post)
hash: "#10013173"
host: "stackoverflow.com"
hostname: "stackoverflow.com"
href: "https://stackoverflow.com/questions/10012966/change-url-with-bookmarklet/10013173#10013173"
origin: "http://stackoverflow.com"
pathname: "/questions/10012966/change-url-with-bookmarklet/10013173"
port: ""
protocol: "http:"
search: ""
Upvotes: 4
Reputation: 3494
Here's an example of the Regex to use in a C# unit test. Since you're not familiar with regex, the pattern is the same as your source url, except with two capture groups: one for the class (?<class>[^/]+)
, and one for the id (?<id>[^/]+)
. How each works is that it takes one or more characters (the plus) that isn't a slash (^/)
and stores it in a regex group of the name in the angle brackets.
var source = "http://www.domain.com/events/13097/article";
var expected = "http://www.domain.com/admin/edit.php?class=events&id=13097";
var pattern = "http://www.domain.com/(?<class>[^/]+)/(?<id>[^/]+)/article";
var r = new Regex(pattern);
var actual = r.Replace(source, "http://www.domain.com/admin/edit.php?class=${class}&id=${id}");
Assert.AreEqual(expected, actual);
Upvotes: 0
Reputation: 207501
//var str = window.location.href;
var str = "http://www.example.com/events/13097/article";
var re = /events\/(\d+)\//;
var match = str.match(re);
var newURL = "http://www.example.com/admin/edit.php?class=events&id=" + match[1];
alert(newURL);
Upvotes: 0