Javascript,将字符串插入另一个URL字符串

时间:2016-03-11 19:14:46

标签: javascript jquery

我不确定如何编写公式来执行此操作...我需要这样做:

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"

基本上我总是试图在原始网址中的upload/之后插入另一个字符串细分。我已经考虑过使用position,但我没有固定的位置,因为current_url赢得的总长度不一样。唯一不变的是我知道字符串需要在upload/之后插入,无论它在哪里

3 个答案:

答案 0 :(得分:7)

current_url.replace("upload/","upload/{NEWSOMETHING}/")

如果您的字符串为var current_url = "http://something.random.com/something/something/upload/something/c_fit/something_else/c_fit/";,并且您想要替换上传和最后一个c_fit之间的所有内容,那么current_url.replace(/\/upload\/.*\/c_fit\//,"/upload/"+"<YOUR_STRING>"+"/c_fit/"),但您只想在上传和第一个c_fit之间替换current_url.replace(/\/upload\/.*?\/c_fit\//,"/upload/"+"<YOUR_STRING>"+"/c_fit/")

答案 1 :(得分:0)

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

答案 2 :(得分:0)

您可以轻松地将字符串拆分为静态文本&#34;上传&#34;。

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