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("/");
Related
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");
Here is a working code I have to get a specific portion of a URL string:
const movieName = "frozen_2019";
const courseName = "olaf_is_enjoying_living_his_dream_1";
const source = "your majesty from https://example.com/english/courses/frozen_2019/olaf_is_enjoying_living_his_dream_1/voices/references/translate/do%20you%20hear%20that.mp3";
console.log(getSourceError(source)); // result
function getSourceError(source) {
const a = source.substring(source.indexOf(courseName) + courseName.length + 1);
const b = a.substring(a.lastIndexOf("/"));
return a.replace(b , "");
}
Although it's working as expected but I think there should be a cleaner solution to do this...
As you see I want the string between courseName and the file name at the end of the URl.
I'm not completly sure what you mean by cleaner solution but this is a one-liner line with regex supposing you got the same variable names like in your snippet. Is this what you wanted to achieve? You can trim the last and first character to remove the slashes if needed.
const source = "your majesty from https://example.com/english/courses/frozen_2019/olaf_is_enjoying_living_his_dream_1/voices/references/translate/do%20you%20hear%20that.mp3";
const courseName = "olaf_is_enjoying_living_his_dream_1";
let extracted = source.match("(?<="+courseName+").*\/");
console.log(extracted);
As you see I want the string between courseName and the file name at
the end of the URL.
When manipulating URL strings, it's often a good idea to split the string into an array using:
let myURLArray = myURLString.split('/');
Then, in this situation, you can use:
indexOf()
splice()
join()
to return the section of the URL that you want.
Working Example:
const courseName = "olaf_is_enjoying_living_his_dream_1";
const source = "your majesty from https://example.com/english/courses/frozen_2019/olaf_is_enjoying_living_his_dream_1/voices/references/translate/do%20you%20hear%20that.mp3";
let sourceArray = source.split('/');
let courseNameIndex = sourceArray.indexOf(courseName);
let urlSectionArray = sourceArray.splice((courseNameIndex + 1), ((sourceArray.length - 1) - courseNameIndex - 1));
let urlSection = urlSectionArray.join('/');
console.log(urlSection);
Hi if your source is consinstent with its structure you can split and join the pieces you require.
source.split('/').splice(7,3).join('/')
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("/");
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';
I have an url that looks like this:
http://localhost/assets/upload/img/hw6dNDBT-36x36.jpg
I want to extract hw6dNDBT.jpg, from the url above.
I tried playing around with regex patterns /img\/.*-/ but that
matches with img/hw6dNDBT-.
How can I do this in JavaScript?
try this:
var url = 'http://localhost/assets/upload/img/hw6dNDBT-36x36.jpg';
var filename = url.match(/img\/(.*)-[^.]+(\.[^.]+)/).slice(1).join('');
document.body.innerHTML = filename;
i would use split() method:
var str = "http://localhost/assets/upload/img/hw6dNDBT-36x36.jpg";
var strArr = str.split("/");
var size = strArr.length - 1;
var needle = strArr[size].split("-");
var fileTypeArr = strArr[size].split(".");
var name = needle[0]+"."+fileTypeArr[fileTypeArr.length-1];
name should now be your searched String so far it contains no / inside it
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
/[^\/]+$/ should match all characters after the last / in the URL, which seems to be what you want to match.
No regex:
//this is a hack that lets the anchor tag do some parsing for you
var parser = document.createElement('a');
parser.href = 'http://localhost/assets/upload/img/hw6dNDBT-36x36.jpg';
//optional if you know you can always trim the start of the path
var path = parser.pathname.replace('/assets/uploads/');
var parts = path.split('/');
var img = '';
for(var i=0; i<parts.length; i++) {
if (parts[i] == 'img') {
//since we know the .jpg always follows 'img/'
img = parts[i+1];
}
}
Ah, you were so close! You just need to take your regex and use a capturing group, and then add a littttle bit more!
img\/(.*)-.*(\..*)
So, you can use that in this manner:
var result = /img\/(.*)-.*(\..*)/.exec();
var filename = result[1] + result[2];
Honestly capturing the .jpg, is a little excessive, if you know they are all going to be JPG images, you can probably just take out the second half of the regex.
Incase you are wondering, why do we uses result[1] and result[2]? Because result[0] stores the entire match, which is what you were getting back. The captured groups, which is what we create when we use the parentheses, are stored as the indexes after 0.
Here is some one-liner:
var myUrl = 'http://localhost/assets/upload/img/hw6dNDBT-36x36.jpg',
myValue = myUrl.split('/').pop().replace(/-(?=\d).[^.]+/,'');
We take everything after the last slash then cut out the dimension part.