Javascript to grab parts of the URL - javascript

I've looked through tons of great posts on pulling query string parameters, and even using regex to grab parts of the URL path. But, it didn't really answer what I'm trying to do.
I need to be able to grab the current URL a user is on and parse out only parts of the pathname, and capture them into separate variables. I don't care about the query string parameters I only want these key parts.
http://www.domain.com/part1/part2/part3/part4
var1=part1
var2=part2
var3=part3
var4=part4
My Javascript is a bit rusty, so any guidance on this would be great!

This solution will split up your string using the slash as a separator, ignoring the protocol.
var url = "http://www.domain.com/part1/part2/part3/part4"
var parts = url.split('/').splice(2);
console.log(parts);
var baseUrl = parts[0];
var part1 = parts[1];
var part2 = parts[2];
var part3 = parts[3];
var part4 = parts[4]

As users in the comments mentioned, the url string is no different than any other string. You can easily just use the string split method to return an array of strings between the / character
To get the href location you can use window.location.href or location.href
var url_str = window.location.href;
The str.split() function takes a separator parameter in this case '/' and returns an array of strings that were found. For example it would return this given your example url http://www.domain.com/part1/part2/part3/part4:
var arr = url_str.split('/');
["http:", "", "www.domain.com", "part1", "part2", "part3", "part4"]
The array .slice(begin,end) method returns a portion of the array from the begin to end(default end of the array) parameters (both zero based, first element = 0, 10th = 9).
To get the last 4 parts of our example array we do the following:
var values = arr.slice(3);
["part1", "part2", "part3", "part4"]
Now you can either access the array directly to get each value or assign them to variables:
console.log("Your first folder is "+values[0]); //direct access
or
var var1 = values[0];
var var2 = values[1];
var var3 = values[2];
var var4 = values[3];
console.log("Your first folder is " + var1]); //variable alias

This is one way to get the url parts like you want.
var url = "http://www.domain.com/part1/part2/part3/part4"
var parts = url.match(/.+w{3}\.\w+\.\w{3}\/(\w+)\/(\w+)\/(\w+)\/(\w+)/);
console.log(parts);
var baseUrl = parts[0];
var part1 = parts[1];
var part2 = parts[2];
var part3 = parts[3];
var part4 = parts[4]
But again, as cyberbit and Patrick have mentioned, you can simply do url.split('/') to get the parts. That way you don't have to worry about how many parts you get in the url. Thanks.

Related

How to extract query string parameters from URL in JavaScript

I have a URL
https://www.yellowpages.com/search?search_terms=Generator+Repair&geo_location_terms=Adamsville%2C+Alabama
I want to get search_terms (Generator+Repair) and geo_location_terms (Adamsville%2C+Alabama)
How I can do this?
The easiest and most idiomatic way to do this in JavaScript is using the URL class:
const url = new URL('https://www.yellowpages.com/search?search_terms=Generator+Repair&geo_location_terms=Adamsville%2C+Alabama')
console.log(url.searchParams.get('search_terms'));
console.log(url.searchParams.get('geo_location_terms'));
MDN reference here.
You can use the following Javascript code to store the GET parameters into an object:
<script>
var URL = "https://www.yellowpages.com/search?search_terms=Generator+Repair&geo_location_terms=Adamsville%2C+Alabama";
var result = {};
URL.substring(URL.indexOf("?") + 1).split('&').forEach(function(x){
var arr = x.split('=');
arr[1] && (result[arr[0]] = arr[1]);
});
console.log(result.search_terms);
//OUTPUT: "Generator+Repair"
console.log(result.geo_location_terms);
//OUTPUT: "Adamsville%2C+Alabama"
</script>
You can use the following regex to get the 2 values:
/search_terms=(.*)&geo_location_terms=(.*)/
This is a very basic regex, that starts by matching 'search_terms=' then creates a Group that matches any number of any char up to the '&' sign, then matches 'geo_location_terms=' and finally creates a Group that matches any number of any char.
Your desired output will be in Group 1 and Group 2.
How to use:
var url = 'https://www.yellowpages.com/search?search_terms=Generator+Repair&geo_location_terms=Adamsville%2C+Alabama';
var regex = /search_terms=(.*)&geo_location_terms=(.*)/;
var match = url.match(regex);
var search_terms = match[1];
var geo_location_terms = match[2];

regex: get string in url login/test

I have a url
https://test.com/login/param2
how do I get the the second parameter "param2" from the url using REGEX?
the url can also be
https://test.com/login/param2/
So the regex should work for both urls.
I tried
var loc = window.location.href;
var locParts = loc.split('/');
and then looping through locParts, but that seems inefficient.
The "param2" can be have number, alphatical character from a-z, and a dash.
Use String#match method with regex /[^\/]+(?=\/?$)/.
var a = 'https://test.com/login/facebook',
b = 'https://test.com/login/facebook/';
var reg = /[^\/]+(?=\/?$)/;
console.log(
a.match(reg)[0],
b.match(reg)[0]
)
Or using String#split get last non-empty element.
var a = 'https://test.com/login/facebook',
b = 'https://test.com/login/facebook/';
var splita = a.split('/'),
splitb = b.split('/');
console.log(
splita.pop() || splita.pop(),
splitb.pop() || splitb.pop()
)
If you don't mind using JS only (so no regex), you can use this :
var lastParameter = window.location.href.split('/').slice(-1);
Basicaly, like you, I fetch the URL, split by the / character, but then I use the splice function to get teh last element of the split result array.
Regular expressions might be compact, but they're certainly not automatically efficient if you can do what you want without.
Here's how you can change your code:
var loc = 'https://test.com/login/facebook/'; // window.location.href;
var locParts = loc.split('/').filter(function(str) {return !!str});
var faceBookText = locParts.pop();
console.log(faceBookText);
The filter removes the last empty item you would get if the url ends with '/'. That's all you need, then just take the last item.

How to extract last value in the URL before the last / separator using JQuery

I have this URL:
http://test.com/en/country/city
Im using lastIndexOf to obtain "city" but I want to obtain "country"
window.location.href.substring(window.location.href.lastIndexOf('/') + 1);
Is this posible with lasIndexOf or there is another function available for this case?
Thank you in advance!
You can split your url by / and take needed element (first remove http:// part):
var str = 'http://test.com/en/country/city';
str = str.replace('http://', '');
var parts = str.split('/');
console.log(parts);
alert(parts[2]+', '+parts[3]);
Try:
var fragment = "http://test.com/en/country/city";
var array_fragment = fragment.split('/');
var city = array_fragment[array_fragment.length - 1]
var country = array_fragment[array_fragment.length - 2]
alert(country)
You could do something like this:
var url = "http://test.com/en/country/city"
var urlParts = url.split("/")
urlParts[urlParts.length - 1] (which would equal to "city")
urlParts[urlParts.length - 2] (which would equal to "country")
Basically split on each occurence of "/" and pick the correct item from the returned array.
Is this posible with lastIndexOf?
Yes, it is possible.
Let's say
x="http://test.com/en/country/city"
We get the position of the last /
y=x.lastIndexOf("/");//26
We get the position of the second last /
z=x.lastIndexOf("/",y-1);//18
To extract the country, we now use substring as follows
x.substring(z+1,y)//country
Use split function to get second last value.
Try this
var url='http://test.com/en/country/city';
var splitArray=url.split('/');
alert(splitArray[splitArray.length-2]);
Try something like this.
var url = window.location.href;
var urlArray = url.split("/");
urlArray[urlArray.length-1] //City
urlArray[urlArray.length-2] //Country

Javascript, insert string into another URL string

Not sure how I would go about writing a formula to do this... I need to do:
current_url = "http://something.random.com/something/something/upload/something/something_else"
new_url = "http://something.random.com/something/something/upload/{NEWSOMETHING}/something/something_else"
Basically I'm always trying to insert another string segment exactly after the upload/ in the original URL. I've thought about using position but I don't have a fixed position because current_url won't always be the same length. The only constant is that I know the string needs to be inserted after upload/, wherever it may be
current_url.replace("upload/","upload/{NEWSOMETHING}/")
If your string is var current_url = "http://something.random.com/something/something/upload/something/c_fit/something_else/c_fit/"; and you want to replace everything in between upload and the last c_fit then current_url.replace(/\/upload\/.*\/c_fit\//,"/upload/"+"<YOUR_STRING>"+"/c_fit/") but you just want to replace between upload and the first c_fit then current_url.replace(/\/upload\/.*?\/c_fit\//,"/upload/"+"<YOUR_STRING>"+"/c_fit/")
var current_url = "http://something.random.com/something/something/upload/something/something_else";
var chunks = current_url.split("/");
var str = [];
var s = chunks.shift();
while(s != "upload"){
str.push(s);
s = chunks.shift();
}
var new_url = str.join('/')+"/upload/{new something}/something/something_else";
alert(new_url);
You could easily split the string on the static text "upload".
var current_url = "http://something.random.com/something/something/upload/something/something_else";
var splitArray = current_url.split("upload");
var additionalParameter = "What_ever_comes_after_upload"
var new_url = splitArray[0] + "upload/" + additionalParameter + splitArray[1];
alert(new_url);

Split text with a single code

var objname = "Image1-123456-789.png"
quick question i wanted to split this text without match them together again.
here is my code
var typename = objname.split("-");
//so it will be Image1,123456,789.png
var SplitNumber = typename[1]+'-'+typename[2];
var fullNumber = SplitCode.split('.')[0];
to get what i wanted
my intention is to get number is there anyway i can split them without join them and split again ?
can a single code do that perfectly ? my code look like so many job.
i need to get the 123456-789.
The String.prototype.substring() method extracts the characters from a string, between two specified indices, and returns the new sub string.
This method extracts the characters in a string between "start" and "end", not including "end" itself.
var objname = "Image1-123456-789.png";
var newname = objname.substring(objname.indexOf("-")+1, objname.indexOf("."));
alert(newname);
An alternate can be using Join. You can use slice to fetch range of values in array and then join them using -.
var objname = "Image1-123456-789.png";
var fullnumber = objname.split("-").slice(1).join("-").split(".")[0];
alert(fullnumber)
Reference
Join Array from startIndex to endIndex
Here is your solution
var objname = "Image1-123456-789.png";
var typename= objname.split("-");
var again=typename[2];
var again_sep= again.split(".");
var fullNumber =typename[1]+'-'+again_sep[0];

Categories

Resources