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);
Related
using jQuery; to add something to a url after the last /
for example add sale to:
/gender/category/brand/
so it becomes:
/gender/category/brand/sale
However due to the way the URL's are generated and built I can't just always say 'add it to the end of a URL' as there are sometimes ?query strings on the end for example:
/gender/category/brand/?collection=short&colour=red
I just can't figure out how I can add sale after the final / and always before a ?query string if one exists.
Searching through stackoverflow I've seen some bits about extracting content after the last / but not this, is this possible? I really would appreciate help getting this sorted.
EDIT - The solution
Thanks too all for your help but I was able to adapt Shree's answer the easiest to get this which did what I needed:
if(window.location.href.indexOf("sale") > -1) {
} else {
var raw = window.location.href;
var add = 'sale';
var rest = raw.substring(0, raw.lastIndexOf("/") + 1);
var last = raw.substring(raw.lastIndexOf("/") + 1, raw.length);
var newUrl = rest + add + last;
window.location.href = newUrl;
}
Use substring with lastIndexOf.
var raw = '/gender/category/brand/?collection=short&colour=red';
var add = 'sale';
var rest = raw.substring(0, raw.lastIndexOf("/") + 1);
var last = raw.substring(raw.lastIndexOf("/") + 1, raw.length);
var newUrl = rest + add + last;
console.log(newUrl);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
In vanilla javascript
var a = "/gender/category/brand/?collection=short&colour=red";
var lastIndexPosition = a.lastIndexOf('/');
a = a.substring(0,lastIndexPosition+1)
+"sale"
+a.substring(lastIndexPosition+1 , a.length);
console.log(a);
By using a reusable function in Javascript:
You can use lastIndexOf and get the last '/' index position and append your new data there.
The lastIndexOf() method returns the position of the last occurrence
of a specified value in a string.
Using this you can send any parameter into function there by it is reusable.
function insert(main_string, ins_string, pos) {
return main_string.slice(0, pos) + ins_string + main_string.slice(pos);
}
var url = "/gender/category/brand/?collection=short&colour=red"
url = insert(url, 'sale', url.lastIndexOf("/") + 1)
console.log(url)
Here is a working DEMO
An alternative, use .split("?") to separate at the ? then combine them back, eg:
// Example with querystring
var url = '/gender/category/brand/?collection=short&colour=red'
var parts = url.split("?");
var newurl = parts[0] + "sale" + "?" + (parts[1]||"")
console.log(newurl)
// Test without querystring
var url = '/gender/category/brand/'
var parts = url.split("?");
var newurl = parts[0] + "sale" + (parts[1]||"")
console.log(newurl)
The (parts[1]||"") handles the case where there isn't a querystring.
I have a variable that returns me the url of an image, and in this url the id of the image can vary the quantity of numbers... what would be the best way to complement the id like this:
As it is: http://mydomain.com.br/arquivos/ids/1318090/94842_1.jpg
How to stay: http://mydomain.com.br/arquivos/ids/1318090-500-500/94842_1.jpg
In short, I need to add the "-500-500" into id
Sorry... A Example:
var a = "http://mydomain.com.br/arquivos/ids/1318090/94842_1.jpg";
var b = "-500-500";
var position = 43;
var output = [a.slice(0, position), b, a.slice(position)].join('');
console.log(output);
You can do something like following:
var url = "http://mydomain.com.br/arquivos/ids/1318090/94842_1.jpg";
var index = url.lastIndexOf("/");
var new_url = url.slice(0, index) + "-500-500" + url.slice(index);
link = link.split("/").reduce((r,c,i)=>r+c+i===5?"-500-500": "","").join("/");
Simply add it behind the 6th element ( that are seperated by / ) .
you have not shown any progress what you did! How about i gave you the hint?
assign a variable to your string, split it using \ and then find the exact occurrence to change by this [0] of course change the number according to your desire where change is required.
Now get your new string and concate with old in a way that you get desired results. Example
var str = "http://mydomain.com.br/arquivos/ids/1318090/94842_1.jpg";
var newstr = str.split('/')[5];
var prepstr = newstr + "something";
then finally,
str + prepstr;
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.
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
I want to get the first part of a filename from the full filename, for example, from:
bee_gees_-_stayin_alive.mp3
I want to return: bee_gees_-_stayin_alive
How can I do it?
var filename = file.name;
var name = filename.split('.');
var lastarray = name.length;
var names = filename.split('.')[lastarray];
Get the index of the last period in the string and get the part of the string before that.
Example:
var fullName = "bee_gees_-_stayin_alive.mp3";
var name = fullName.substr(0, fullName.lastIndexOf('.'));
Demo: http://jsfiddle.net/sfB2v/
You should take a look at the very basic form of regular expressions since this question could easily be solved by googling a bit, but here I go:
the dumb way
var filename = "bee_gees_-_stayin_alive.mp3"
var name = filename.split('.')[0]
the proper way
var filename = "bee_gees_-_stayin_alive.mp3"
var name = filename.match(/[a-zA-Z_-]*/)[0]