I'm trying to make a bookmarklet that will take part of an URL and redirect to the new URL, but I need to change two parts of the URL that are separate.
The base URL could be:
78.media.tumblr.com/fc87fac5ea0d88e1e22a214d25a169ee/tumblr_p3fjmdiF7f1r9qk1io1_1280.png
I need it to end like this:
s3.amazonaws.com/data.tumblr.com/fc87fac5ea0d88e1e22a214d25a169ee/tumblr_p3fjmdiF7f1r9qk1io1_raw.png
So I need to replace "78.media.tumblr.com" and "1280"
I've tried coming up with something using window.location.assign and location.href.replace but I'm pretty new and couldn't figure it out.
You can do this with regex and window.location.href. This is assuming you are only looking at tumbler though. If you're not, there would be another step in the regex.
// first get the url
var url = window.location.href;
// Use regex to keep only the parts we want and replace the others
var newUrl = url.replace(/.*(\.tumblr.*\_).*(\..*)/, 'http://s3.amazonaws.com/data$1raw$2')
// go to the new page
window.location.href = newUrl;
In general, you can just replace the parts of the string using String.prototype.replace. Depending on how flexible you need the matching to be you can adjust the regexes to be more or less 'matchy'.
const startUrl = '78.media.tumblr.com/fc87fac5ea0d88e1e22a214d25a169ee/tumblr_p3fjmdiF7f1r9qk1io1_1280.png'
const endUrl = 's3.amazonaws.com/data.tumblr.com/fc87fac5ea0d88e1e22a214d25a169ee/tumblr_p3fjmdiF7f1r9qk1io1_raw.png'
const tumblerRegex = /.*\.tumblr\.com/
const numberRegex = /_\d{4}/
function transform (start) {
return start.replace(tumblerRegex, 's3.amazonaws.com/data.tumblr.com').replace(numberRegex, '_raw')
}
console.log(transform(startUrl) == endUrl)
Related
Let me explain what I mean:
I want to redirect from https://example.net/category/83745/my-first-post to https://myredirect.net/my-first-post but without considering /category/numbers/
For the moment I work with this:
if(window.location.pathname == '/category/83745/my-first-post')
{
window.location.href="https://myredirect.net/my-first-post";
}
And it is working fine but as I described I need to remove /category/numbers/ because they could be different and only consider this part /my-first-post for the redirection.
Thanks in advance.
if you want to just ignore the first 2 parts dynamically and only care about the last part of the URL then just do the following:
var stringContains = function (str, partial){
return (str.indexOf(partial) > -1);
};
var url = '/category/83745/my-first-post';
if(stringContains(url, "/category")){
var parts = a.split("/");
window.location.href = parts[parts.length-1];
}
You can use String's methods lastIndexOf and slice:
var path = window.location.pathname;
window.location.href = "https://myredirect.net" + path.slice(path.lastIndexOf('/') + 1);
Use Regex. Something like
if(window.location.pathname.match(/\/category\/\d+\/my\-first\-post$/)
{
window.location.href="https://myredirect.net/my-first-post";
}
You can run a regular expression match on the pathname
if(window.location.pathname.match(/my-first-post$/)) {
window.location.href='/my-first-post';
}
More on regexes: https://www.regular-expressions.info/
Another good tool for building and testing regexes: https://regex101.com/
Edit:
To give an example of how to regex according to the more fleshed out specs from Chris G
let pathmatch = window.location.pathname.match(/([^\/]+)$/g);
window.location.href = '/' + pathmatch[0];
Thus, regex can be utilized to grab any pattern and use it later.
IF there is a need to make sure the pathname contains category and/or numbers, it is easily added in to the pattern. This one simply disregards anything before the last forward slash (/)
I'm changing current user's path through a function:
function setSomeValue(someValues) {
var query = '';
for (var i = 0; i < someValues.length; i++) {
query += someValues[i] + ',';
}
if ('URLSearchParams' in window) {
var searchParams = new URLSearchParams(window.location.search);
searchParams.set("paramName", query);
var newRelativePathQuery = window.location.pathname + '?' + searchParams.toString();
history.pushState(null, '', newRelativePathQuery);
}
}
As you can see, I'm adding to user's location new words and want new location to be like this:
www.site.com?paramName=value1,value2,
But browser converts my commas into %2C so I get this:
www.site.com?paramName=value1%2Cvalue2%2C
What should be done to make pushing commas to URL possible?
(copy & paste from several comments)
It might be due to URLSearchParams and its toString method implementation - but we can’t know, because you have not shown us what that actually is. If that is not deliberately encoding the comma, and the browser simply does it automatically - then there’s little you can do about that.
If newRelativePathQuery contains the encoded versions already, maybe they could be replaced back to normal commas. But if history.pushState does it, then “other ways” to create the URL itself won’t help you much.
Since a debug output showed that newRelativePathQuery contains the encoded commas already, you can try and replace them back to commas, and see if that “survives” being pushed to the history then.
It's a little hacky, but here's one solution. Let's say we want to use URL's searchParams.set() to set ids=1,2,3,4 in our query string.
If you just do url.searchParams.set("ids", "1,2,3,4"), the URL will have ids=1%2C2%2C3%2C4. To avoid that encoding, first set ids=LIST_OF_IDS_PLACEHOLDER, get the URL as a string, and then replace LIST_OF_IDS_PLACEHOLDER with 1,2,3,4, like this:
const myList = [1,2,3,4],
url = new URL(document.location.href); // or however you get your URL object
url.searchParams.set("ids", "LIST_OF_IDS_PLACEHOLDER");
const newUrlString = url.toString().replace("LIST_OF_IDS_PLACEHOLDER", ids.join(','));
console.log(newUrlString); // this will include: ids=1,2,3,4
I want to get a specific part of a url between the third and fourth slashes of a link on the page.
EDIT: Sorry I don't think I was clear the first time, I meant getting the specific part of the url OF A LINK found on the page.
var getSegment = function (url, index) {
return url.replace(/^https?:\/\//, '').split('/')[index];
}
Usage:
getSegment("http://domain.com/a/b/c/d/e", 4); // "d"
The replace makes sure that the first two slashes after the protocol (http or https) don't count.
Here's a working example of getting a particular path segment.
Code:
var url = "www.test.com/one/two/three?p1=v&p2=v#anc";
var file = url.split('?')[0];
var pathanddomain = file.split('/');
var path = pathanddomain.splice(1, pathanddomain.length-1);
var pathIndexToGet = 2;
document.write(path[pathIndexToGet]);
If you want to do this for the current page, use:
var url = window.location.href;
Also, if your url starts with http(s)://, you will need to remove this.
I'd suggest:
var link = 'http://www.example.com/directory1/directory2/directory3/directory4/index.html';
console.log(link.split('/')[5]);
JS Fiddle demo.
The reason we're using [5] not [4] is because of the two slashes at the beginning of the URL, and because JavaScript arrays are zero-based.
you should elaborate you question and should specify which is your domain, that means on what purpose you are asking that question ??
This may help you:
var urlValue = url.split("/");
Then store urlValue as array.
then pick up third and forth value of the urlvalue on array.
How would I go about trimming/stripping the URL down to the page name...
So: http://www.BurtReynoldsMustache.com/whatever/whoever/apage.html
Would become: apage.html
Any ideas?
you do not need jquery:
var url = window.location.href;
var page = url.substring(url.lastIndexOf('/') + 1);
Edit: a good point of the possible query string:
// it might be from browser & / anywhere else
var url = window.location.href;
url = url.split('#').pop().split('?').pop();
var page = url.substring(url.lastIndexOf('/') + 1);
ok, if the location object is available, use pathname gives better result as show below, however, a url can be a string or something directly from text field or span/label. So above solution should have its place.
With location and any link (<a>) elements on the page, you get a load of properties that give you specific parts of the URL: protocol, host, port, pathname, search and hash.
You should always use these properties to extract parts of the URL in preference to hacking about with href and probably getting it wrong for corner cases. For example, every solution posted here so far will fail if a ?query or #fragment is present. The answers from Rob and digitalFresh attempt to cope with them, but will still fail if a / character is present in the query string or fragment (which is valid).
Instead, simply:
var pagename= location.pathname.split('/').pop();
Most of the solutions here are not taking advantage of the window.location object. The location object has this wonderful thing called pathname which returns just the path, no query string, host, protocol, hash, etc.
var mypage = window.location.pathname.split("/").pop();
You could do something like this:
document.location.href.split('/').pop();
Edit: you probably want to get rid of the query string if there is one also:
document.location.href.split('/').pop().split('?').shift();
Edit 2: this will also ignore an anchor in the url if there is one
document.location.href.split('/').pop().split(/\?|#/).shift();
This should also exclude query and hash values.
var path = location.href;
path = path.substring(path.lastIndexOf("/") + 1);
path = path.split("?")[0].split("#")[0];
console.debug(path);
Haven't tested so compeltely guessed, but I'm sure something like this will do :-)
var url = 'http://www.BurtReynoldsMustache.com/whatever/whoever/apage.html';
var page = url.split('/');
alert(page[page.length-1]);
EDIT Tested under jsfiddle and it was wrong, the above code should now work :-)
Is it possible to create a new Location object in javascript? I have a url as a string and I would like to leverage what javascript already provides to gain access to the different parts of it.
Here's an example of what I'm talking about (I know this doesn't work):
var url = new window.location("http://www.example.com/some/path?name=value#anchor");
var protocol = url.protocol;
var hash = url.hash;
// etc etc
Is anything like this possible or would I essentially have to create this object myself?
Well, you could use an anchor element to extract the url parts, for example:
var url = document.createElement('a');
url.href = "http://www.example.com/some/path?name=value#anchor";
var protocol = url.protocol;
var hash = url.hash;
alert('protocol: ' + protocol);
alert('hash: ' + hash);
It works on all modern browsers and even on IE 5.5+.
Check an example here.
How about use the standard URL object?
const url = new URL("http://www.example.com/some/path?name=value#anchor");
const { hash } = url;
Then console.log(hash) will output #anchor.
Warning: This interface is a bit new, so, if you're not using a transpiler, please, check the compatibility table and do your tests at target browsers.
You can leverage the power of an anchor element
var aLink = document.createElement("a");
aLink.href="http://www.example.com/foo/bar.html?q=123#asdf";
alert(aLink.pathname);
You can parse it in a regex to get the parts as matches... I don't have the full code right now, but this can be used to get the querydata:
var myUrl = window.location.href;
var matches = myUrl.match(/([^\?]+)\?(.+)/);
var queryData = matches[2];
matches[0] is the full string, matches(1) is the first part of the URL (up to the ?)... you could build up a regular expression to parse each part of a string url if you want...
You can also use one of the many libraries already out there for this.