james
james

Reputation: 4049

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

Upvotes: 1

Views: 1853

Answers (3)

vcosk
vcosk

Reputation: 2934

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

Upvotes: 7

jdaval
jdaval

Reputation: 640

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

Upvotes: 0

user6050896
user6050896

Reputation:

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

Upvotes: 0

Related Questions