[英]Remove anchor from url - add string to url - and append anchor at the end again
我正在尋找一種可轉換以下URL的jquery解決方案:
http://www.mysite.com/longpage.html#title3
成
http://www.mysite.com/longpage.html?var=1#title3
只需添加“?var = 1”就沒有問題。 但是,錨僅在將其放置在URL的末尾時才起作用。
根據您在問題中所描述的內容,一個簡單的替換就可以解決問題:
"http://www.mysite.com/longpage.html#title3".replace(/(#.+?)$/, '?var=1$1')
這只是普通的JS,因為這就是所有需要的東西。
嘗試:
var href = window.location.href;
if(href.indexOf("#") > 0){
href = href.split("#")[0] + "?var=1#" + href.split("#")[1];
window.location.href = href;
}
例如
var urlParts = location.href.split("#");;
var newUrl = urlParts[0]+"?var="+someVar+(urlParts.length>1?"#"+urlParts[1]:"");
謝謝大家
我們實施了另一個建議的解決方案:
var url = $(this).attr('href');
var pos = url.indexOf('#');
if (pos != -1) {
var newurl = url.substr(0,pos);
var fragment = url.substr(pos, url.length - pos);
}
else {
var newurl = url;
var fragment = '';
}
$(this).attr('href', newurl + '?var=1' + fragment);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.