I have the following link
http://bulk-ccc.aaaa.com/tracking/food?
I need to get the first string after the url which in this case is
tracking
and also the second string
food
how this can be done with JS?
You can use URL interface to parse a URL string. You can try this:
const str = "http://bulk-ccc.aaaa.com/tracking/food?";
const url = new URL(str);
let parts = url.pathname ? url.pathname.split('/').filter(v => !!v) : [];
console.log(parts);
From this parts array you can get your require parts.
You can split the string to get it into an array and then get the needed amount of elements
window.location.pathname.split('/').filter((x, i) => x && i < 3)
Related
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('/')
var str = "https://cdn.fbsbx.com/v/t59.2708-21/68856895_411975049700005_8580443955521388544_n.xls/test.xls?_nc_cat=106&_nc_oc=AQmcm2PVCUFFyUJDJgLs3ZYM4Dg12PX1Wv48Fm0LJ8-Qi8duxOpEVrD2uFgrD9e1pDOXcLpJmbtjbveAm12xczd2&_nc_ht=cdn.fbsbx.com&oh=18eab18ae1d1cf2a95084bba0a002163&oe=5D8F8124";
var n = str.substring(str.indexOf("\\.") +1 , str.indexOf("?_nc_cat="));
I have this string but my output is :
https://cdn.fbsbx.com/v/t59.2708-21/68856895_411975049700005_8580443955521388544_n.xls/test.xls
How can i get only this .xls?
My other string is :
https://scontent.xx.fbcdn.net/v/t1.15752-9/70629455_2730574856953299_3640328874664919040_n.png?_nc_cat=100&_nc_oc=AQm0m5jryh7zAzyj2R-w7ke0DKQgHM7aYaVkkRjPYDUQ6g-FUAWqVwhnr7qxqISkWMdiNhtp7e8gYMA6gss58poN&_nc_ad=z-m&_nc_cid=0&_nc_zor=9&_nc_ht=scontent.xx&oh=1cbb98fb9484bd3f26b6058808cca889&oe=5E36459B
but again im not getting just word "png" im getting from start link.
I'd use a regular expression, and match word characters while looking ahead for ?:
const getFileType = str => str.match(/\w+(?=\?)/)[0];
console.log(getFileType("https://cdn.fbsbx.com/v/t59.2708-21/68856895_411975049700005_8580443955521388544_n.xls/test.xls?_nc_cat=106&_nc_oc=AQmcm2PVCUFFyUJDJgLs3ZYM4Dg12PX1Wv48Fm0LJ8-Qi8duxOpEVrD2uFgrD9e1pDOXcLpJmbtjbveAm12xczd2&_nc_ht=cdn.fbsbx.com&oh=18eab18ae1d1cf2a95084bba0a002163&oe=5D8F8124"));
console.log(getFileType('https://scontent.xx.fbcdn.net/v/t1.15752-9/70629455_2730574856953299_3640328874664919040_n.png?_nc_cat=100&_nc_oc=AQm0m5jryh7zAzyj2R-w7ke0DKQgHM7aYaVkkRjPYDUQ6g-FUAWqVwhnr7qxqISkWMdiNhtp7e8gYMA6gss58poN&_nc_ad=z-m&_nc_cid=0&_nc_zor=9&_nc_ht=scontent.xx&oh=1cbb98fb9484bd3f26b6058808cca889&oe=5E36459B'));
Simply, Just you have to use the LastIndexof() in the right way to achieve this
str = "https://scontent.xx.fbcdn.net/v/t1.15752-9/70629455_2730574856953299_3640328874664919040_n.png?_nc_cat=100&_nc_oc=AQm0m5jryh7zAzyj2R-w7ke0DKQgHM7aYaVkkRjPYDUQ6g-FUAWqVwhnr7qxqISkWMdiNhtp7e8gYMA6gss58poN&_nc_ad=z-m&_nc_cid=0&_nc_zor=9&_nc_ht=scontent.xx&oh=1cbb98fb9484bd3f26b6058808cca889&oe=5E36459B";
url = str.substring(0,str.indexOf("?"));
ext = str.substring(url.lastIndexOf(".")+1, url.length);
The same will work for any other string as well.
Since it seems you're trying to get the last value from pathname which is preceded by . from URL, so you can use URL API
Simply parse the URL with URL api, take the patname value and split on . and take the last element from splitted array.
var str = "https://cdn.fbsbx.com/v/t59.2708-21/68856895_411975049700005_8580443955521388544_n.xls/test.xls?_nc_cat=106&_nc_oc=AQmcm2PVCUFFyUJDJgLs3ZYM4Dg12PX1Wv48Fm0LJ8-Qi8duxOpEVrD2uFgrD9e1pDOXcLpJmbtjbveAm12xczd2&_nc_ht=cdn.fbsbx.com&oh=18eab18ae1d1cf2a95084bba0a002163&oe=5D8F8124";
let valueExtractor = (str) =>{
let urlParse = new URL(str)
return urlParse.pathname.split('.').pop()
}
console.log(valueExtractor(str))
console.log(valueExtractor("https://cdn.fbsbx.com/v/t59.2708-21/68856895_411975049700005_8580443955521388544_n.xls/test.png?_nc_cat=106&_nc_oc=AQmcm2PVCUFFyUJDJgLs3ZYM4Dg12PX1Wv48Fm0LJ8-Qi8duxOpEVrD2uFgrD9e1pDOXcLpJmbtjbveAm12xczd2&_nc_ht=cdn.fbsbx.com&oh=18eab18ae1d1cf2a95084bba0a002163&oe=5D8F8124"))
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("/");
How to remove parameters with value = 3 from URL string?
Example URL string:
https://www.example.com/test/index.html?param1=4¶m2=3¶m3=2¶m4=1¶m5=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¶m2=3¶m3=2¶m4=1¶m5=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¶m2=3¶m3=2¶m4=1¶m5=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¶m2=3¶m3=2¶m4=1¶m5=3';
const [base, qs] = str.split('?');
const replacedQs = qs.replace(/(^|&)[^=]+=3\b/g, '');
const output = base + (replacedQs ? '?' + replacedQs : '');
console.log(output);
I have a URL which may be formatted like this: http://domain.com/space/all/all/FarmAnimals
or like this: http://domain.com/space/all/all/FarmAnimals?param=2
What regular expression can I use to return the expression FarmAnimals in both instances?
I am trying this:
var myRegexp = /\.com\/space\/[a-zA-Z0-9]*\/[a-zA-Z0-9]*\/(.*)/;
var match = myRegexp.exec(topURL);
var full = match[1];
but this only works in the first instance, can someone please provide an example of how to set up this regex with an optional question mark closure?
Thank you very much!
/[^/?]+(?=\?|$)/
Any non-/ followed by either ? or and end-of-line.
I wouldn't write my own regex here and let the Path class handle it (if those are your two string formats).
string url = "http://domain.com/space/all/all/FarmAnimals";
//ensure the last character is not a '/' otherwise `GetFileName` will be empty
if (url.Last() == '/') url = url.Remove(url.Length - 1);
//get the filename (anything from FarmAnimals onwards)
string parsed = Path.GetFileName(url);
//if there's a '?' then only get the string up to the '?' character
if (parsed.IndexOf('?') != -1)
parsed = parsed.Split('?')[0];
You could use something like this:
var splitBySlash = topURL.split('/')
var splitByQ = splitBySlash[splitBySlash.length - 1].split('?')
alert(splitByQ[0])
Explanation:
splitBySlash will be ['http:','','domain.com', ... ,'all','FarmAnimals?param=2'].
Then splitByQ will grab the last item in that array and split it by ?, which becomes ['FarmAnimas','param=2'].
Then just grab the first element in that.
This
.*\/(.*?)(\?.*)?$
Should capture the part of the string you are looking for as the group 1 (and the query after ? in group 2, if needed).
var url = 'http://domain.com/space/all/all/FarmAnimals?param=2';
//var url = 'http://domain.com/space/all/all/FarmAnimals';
var index_a = url.lastIndexOf('/');
var index_b = url.lastIndexOf('?');
console.log(url.substring(index_a + 1, (index_b != -1 ? index_b : url.length)));