How to get first two URL path segments? - javascript

How to get first two parts of the URL using AngularJS?
For example, I would like to get the two first path of this URL (as admin/password/):
http://localhost:3000/admin/password/57045b10eba5ca1dfd01a8fc4adb4f6c4efc6454b9454514

split the url on "/"
url = window.location.href.split("/")
now you have each word in a sepperate array item, then you can combine them into one string like
console.log(url[0] + url[1] + url[2]);

From Angular $location service:
url([url]);
Return URL when called without any parameter.
Use it like this:
$scope.currentUrl = $location.url();
If you don't need the whole URL, just split it.

You can use URL to get the pathname, then split on / and take the 2 segments you want:
var url = "http://localhost:3000/admin/password/57045b10eba5ca1dfd01a8fc4adb4f6c4efc6454b9454514";
var pathParts = new URL(url).pathname.split('/'); //["", "admin", "password", "57045b10eba5ca1dfd01a8fc4adb4f6c4efc6454b9454514"]
pathParts.slice(1, 3).join('/') + '/'; //"admin/password/"

You can do it using RegExp.
var str = 'http://localhost:3000/admin/password/57045b10eba5ca1dfd01a8fc4adb4f6c4efc6454b9454514';
var reg = str.match(/(?!:\d+)(\/\w+)(\/\w+)/g);
console.log(reg.toString().split('/').slice(1));

Related

Javascript - Remove some part of URL and Add Query after

How can I remove some part of an url and add some query before returning it?
Example:
locahost:8080/product/orders/1.
I want to remove the orders/1 and add /?query="sample".
Use replace function:
location.replace("locahost:8080/product/?query='sample'")
You can get the url by simply doing window.location.href. You can then edit it by copying it to some new var newURL = window.location.href;
newUrl = newUrl.replace('/orders/1', '/?query=\"sample\"');
window.location.href = newUrl; // execute this to pass on the parameters to the current page.
Suppose you have url like this in variable1, let say like this
var variable1 = 'http://locahost:8080/product/orders/1'; //here you can get the actual browser url using `window.location.href`and assign it to `variable1`
just use replace function:
var final_text = variable1.replace('/orders/1','?query=sample');
you will get the following output, you do console.log(final_text);
http://locahost:8080/product?query=sample
You can try something like
var url = window.location.href;
var query = "somestring" ;
window.location.replace(url + "&" + somestring);
removing the / pieces:
var newloc = url.substring(0, url.search("/")) + query;
window.location.replace(newloc);

Get string between / in URL

Let's say I have the following URL https://www.google.com/en-gb/test-page.
I'm trying to extract whatever is after the domain name, in this case en-gb, however, with my approach, it's currently spitting out the entire slug.
I.e.
var pathname = window.location.pathname.substr(1);
console.log(pathname);
Will log out:
en-gb/test-page
How can I get it so that it only log out en-gb?
Just split the url with the / delimiter
const url = 'https://www.google.com/en-gb/test-page';
console.log(url.split('/')[3]);
You can use URL.pathname
Code:
const url = new URL('https://www.google.com/en-gb/test-page');
const str = url.pathname.split('/')[1];
console.log(str);
Split on a slash:
var [pathname] = window.location.pathname.substr(1).split("/");

Javascript how to remove parameter from URL sting by value?

How to remove parameters with value = 3 from URL string?
Example URL string:
https://www.example.com/test/index.html?param1=4&param2=3&param3=2&param4=1&param5=3
If you are targeting browsers that support URL and URLSearchParams you can loop over the URL's searchParams object, check each parameter's value, and delete() as necessary. Finally using URL's href property to get the final url.
var url = new URL(`https://www.example.com/test/index.html?param1=4&param2=3&param3=2&param4=1&param5=3`)
//need a clone of the searchParams
//otherwise looping while iterating over
//it will cause problems
var params = new URLSearchParams(url.searchParams.toString());
for(let param of params){
if(param[1]==3){
url.searchParams.delete(param[0]);
}
}
console.log(url.href)
There is a way to do this with a single regex, using some magic, but I believe that would require using lookbehinds, which most JavaScript regex engines mostly don't yet support. As an alternative, we can try splitting the query string, then just examining each component to see if the value be 3. If so, then we remove that query parameter.
var url = "https://www.example.com/test/index.html?param1=4&param2=3&param3=2&param4=1&param5=3";
var parts = url.split(/\?/);
var params = parts[1].replace(/^.*\?/, "").split(/&/);
var param_out = "";
params.forEach(function(x){
if (!/.*=3$/.test(x))
param_out += x;
});
url = parts[0] + (param_out !== "" ? "?" + param_out : "");
console.log(url);
You could use a regular expression replace. Split off the query string and then .replace &s (or the initial ^) up until =3s:
const str = 'https://www.example.com/test/index.html?param1=4&param2=3&param3=2&param4=1&param5=3';
const [base, qs] = str.split('?');
const replacedQs = qs.replace(/(^|&)[^=]+=3\b/g, '');
const output = base + (replacedQs ? '?' + replacedQs : '');
console.log(output);

How to strip / replace something from a URL?

I have this URL
http://192.168.22.124:3000/temp/box/c939c38adcf1873299837894214a35eb
I want to replace the last part of my URL which is c939c38adcf1873299837894214a35eb with something else.
How can I do it?
Try this:
var url = 'http://192.168.22.124:3000/temp/box/c939c38adcf1873299837894214a35eb';
somethingelse = 'newhash';
var newUrl = url.substr(0, url.lastIndexOf('/') + 1) + somethingelse;
Note, using the built-in substr and lastIndexOf is far quicker and uses less memory than splitting out the component parts to an Array or using a regular expression.
You can follow this steps:
split the URL with /
replace the last item of array
join the result array using /
var url = 'http://192.168.22.124:3000/temp/box/c939c38adcf1873299837894214a35eb';
var res = url.split('/');
res[res.length-1] = 'someValue';
res = res.join('/');
console.log(res);
Using replace we can try:
var url = "http://192.168.22.124:3000/temp/box/c939c38adcf1873299837894214a35eb";
var replacement = 'blah';
url = url.replace(/(http.*\/).*/, "$1" + replacement);
console.log(url);
We capture everything up to and including the final path separator, then replace with that captured fragment and the new replacement.
Complete guide:
// url
var urlAsString = window.location.href;
// split into route parts
var urlAsPathArray = urlAsString.split("/");
// create a new value
var newValue = "routeValue";
// EITHER update the last parameter
urlAsPathArray[urlAsPathArray.length - 1] = newValue;
// OR replace the last parameter
urlAsPathArray.pop();
urlAsPathArray.push(newValue);
// join the array with the slashes
var newUrl = urlAsPathArray.join("/");
// log
console.log(newUrl);
// output
// http://192.168.22.124:3000/temp/box/routeValue
You could use a regular expression like this:
let newUrl = /^.*\//.exec(origUrl)[0] + 'new_ending';

converting URL string into slug

I have a string that looks like this "/testpress/about/" and I need to convert it to "about".
I can easily remove testpress by doing the following:
var slug=relativeUrl.replace("testpress", "");
I have not had luck with removing the slashes:
noslash = slug.replace(/\\/g, '');
How can I go about this so I am left with the desired slug?
It is because you are using the wrong slashes
noslash = slug.replace(/\//g, '');
Look here:
> "/testpress/about/".replace(/\//g, '')
'testpressabout'
I like the RegEx method. That way you can see all the path components.
var path = "/testpress/about/";
var pathComponents = path.match(/([^\/]+)/g);
// to get current page... (last element)
var currentPageSlug = pathComponents[pathComponents.length - 1];
This will work regardless of the trailing slash. The good thing is that no matter how deep the URL structure is, you can always get the path components by referencing them as pathComponents[0], pathComponents[1], pathComponents[2], etc ...
With the RegEx method you also do not need to define 'testpress' in the replace/match/split function. That way it makes your code more reusable.
Why don't you use
"testpress/about/".split('\/')
which will yield
["testpress", "about", ""]
and there you have it: second element of the array.
You could also use a regular expression to match everything after the slash but before the end of the string, like so:
var text = "testpress/about";
var slug = text.match(/([^\/]+)\/?$/)[1];
//slug -> "about"
I like #Michael Coxon's answer but the accepted solution doesn't take into account query parameters or things like '.html'. You could try the following:
getSlugFromUrl = function(url) {
var urlComponents = url.match(/([^\/]+)/g),
uri = urlComponents[urlComponents.length - 1];
uri = uri.split(/[\.\?\&]/g);
if (uri.length) {
slug = uri[0];
}
return slug;
};
This should return only the slug and not anything afterwards.
JSBin here: http://jsbin.com/sonowolise/edit?html,js,console

Categories