Get string between / in URL - javascript

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("/");

Related

Access params in URL in JS (React)

I have this URL : http://localhost:3000/#access_token=90kzif5gr8plhtl9286sc1z1qbgoj3&scope=moderation%3Aread&token_type=bearer
and I want to get from this only the access_token value 90kzif5gr8plhtl9286sc1z1qbgoj3
How can I do it in Javascript please ?
Here is the solution:
const url = "http://localhost:3000/#access_token=90kzif5gr8plhtl9286sc1z1qbgoj3&scope=moderation%3Aread&token_type=bearer";
const hash = url.substring(url.indexOf('#') + 1);
let result = hash.split('&')
result = result[0].split('=')
console.log(result[1]); // "90kzif5gr8plhtl9286sc1z1qbgoj3"
Happy coding :)
As you can see in this the simplest way is :
var url_string = "http://localhost:3000/#access_token=90kzif5gr8plhtl9286sc1z1qbgoj3&scope=moderation%3Aread&token_type=bearer";
var url = new URL(url_string);
var c = url.searchParams.get("access_token");
You can try this by splitting the URL string into three strings and using the access token directly then
var url=http://localhost:3000/#access_token=90kzif5gr8plhtl9286sc1z1qbgoj3&scope=moderation%3Aread&token_type=bearer
var firstHalf=url.split('#access_token=')[1];
var required_token=firstHalf.split("&scope")[0];
print the value of required_token.
Required result will be "90kzif5gr8plhtl9286sc1z1qbgoj3"
your text is the string contained in window.location.hash, and a string of that format can be easily turned into a properly decoded key/value store using the URLSearchParams constructor:
const token = new URLSearchParams(window.location.hash).get("access_token");

Get last two params of an URL - javascript

My URL looks like this
stackoverflow.com/questions/ask/format/return
I need to get only format/return from the above URL. I'm able to assign the complete URL to a variable. Currently i'm doing it on split
url.split("/")[4]
url.split("/")[5]
And this is not Generic. What is the better way to achieve this?
The shortest, cleanest way to do this is by using slice on the splitted URL:
url.split("/").slice(-2).join("/")
Just use the length to help you index from the end:
var res = url.split('/')
var last = res[res.length-1]
var pre_last = res[res.length-2]
A genetic solution,
Var URL = url.split("/"); //
Last = URL[URL.length-1]; // return
LastBefore = URL[URL.length-1]; //format
url = "stackoverflow.com/questions/ask/format/return"
URL = url.split("/");
console.log(URL[URL.length-1]) // return
console.log(URL[URL.length-2]) //format
Look for the last and penultimate values:
let spl = url.split("/");
alert(spl[spl.length-2]+' and '+spl[spl.length-1]);
I'd parse the url to a URL, then use match on the pathname. This way it will also work should you have any searchparams (?foo=bar) in your url
const s = "https://stackoverflow.com/questions/ask/format/return";
const uri = new URL(s);
const m = uri.pathname.match(/([^\/]*)\/([^\/]*)$/);
console.log(m);
Note that you'll get an array holding three entries - 0 being the path combined, 1 the first and 2 the last param.
You can use a simple regex /.*\/(.*\/.*)/) to extract exactly what you want.
str.match(/.*\/(.*\/.*)/).pop()
var str = "stackoverflow.com/questions/ask/format/return",
res = str.match(/.*\/(.*\/.*)/).pop();
console.log(res);
var parts = url.split("/");
lastTwo = [parts.pop(), parts.pop()].reverse().join("/");

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';

How to get first two URL path segments?

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));

parsing pathname in url.pathname()

I have a url as below
localhost:1340/promotionDetails/pwd1/pwd2?promotion_id=PROM008765
I used url module for parsing the url for the pathname below is the code
var url=require('url').parse('http://localhost:1340/promotionDetails/pwd1/pwd2? promotion_id=PROM008765', true).pathname
console.log(url);
The output that I got is
/promotionDetails/pwd1/pwd2
I used the split function to get the pwd1 and pwd2 from the path.I want to know if there is anyother way to get pwd1 and pwd2 without using the split function.Any help will be really helpful.
You can regex to get the url directories without using split.
var myurl = "localhost:1340/promotionDetails/pwd1/pwd2?promotion_id=PROM008765";
var match = myurl.match(/[^/?]*[^/?]/g);
/* matches everything between / or ?
[ 'localhost:1340',
'promotionDetails',
'pwd1',
'pwd2',
'promotion_id=PROM008765' ]
*/
console.log(match[2]);//pwd1
console.log(match[3]);//pwd2
Updated 2019 ES6 answer:
You can regex to get the url directories without using split.
const myurl = "localhost:1340/promotionDetails/pwd1/pwd2?promotion_id=PROM008765";
const filteredURL = myurl.match(/[^/?]*[^/?]/g).filter((urlParts) => {
return urlParts !== 'promotionDetails' && urlParts !== 'localhost:1340'
})
const [pwd1, pwd2] = filteredURL;
console.log(pwd1)
console.log(pwd2)

Categories