簡體   English   中英

使用javascript刪除網址字符串的特定部分

[英]Remove a particular part of a url string using javascript

在以下字符串中,

http://blahblah.in/folder1/data?number=1&name= &customerId=123

我正在嘗試驗證URL,也就是說,如果任何querystring參數沒有值,請從URL中刪除該參數。

結果URL將是

http://blahblah.in/folder1/data?number=1&customerId=123

我嘗試使用以下代碼解決上述問題,並且我知道某個地方有一個錯誤-您能幫我找到它嗎?

var url = "http://blahblah.in/folder1/data?number=1&name= &customerId=123";


var tempQuestion = url.split("?");
 var temp = tempQuestion[1].split("=");
var temp2="";
var leng = temp.length;
for(i=0;i<leng;i++){


    if(temp[i].charAt(0)!="&")
        temp2 = temp2.concat(temp[i],"=");
    else 
    {
        temp2 = temp2.concat(temp[i],"");
        var x = temp2.split("&");
        temp2 = temp2.concat(x[0],"=");
    }

}

var result= tempQuestion[0].concat("?",temp2);

只需使用正則表達式如下:

  var url = 'http://blahblah.in/folder1/data?number=1&name=&other=&something=&customerId=123' url = url.replace(/[az]*=&/g,""); console.log(url) // result is: http://blahblah.in/folder1/data?number=1&customerId=123 

我會這樣:

url.replace(/\?.*/, function(qs) {
  return qs.split('&').filter(function(parameterTuple) {
    return parameterTuple.split('=')[1];
  }).join('&');
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM