2017-04-11 67 views
1

在我的地盤我有一個HTML表單類似如下:分離鏈接,並插入到表

<label>Name</lable> 
<input name="username" id="username19" type="text" value=""> 

,讓我們說,在瀏覽器的地址欄中的鏈接是:

https://sitename.com/consulting/order-plan/#ref/testing **

我想要做的事情如下:

從瀏覽器地址欄中選取網址,並按「/」分隔。在這種情況下選擇最後一個單詞後,它將「測試」並將其插入到ID爲「username19」的表單值中

你能幫我用Javascript或jQuery做到這一點嗎?

+1

看看這裏 - http://stackoverflow.com/questions/39619951/regular-expression-for-link/39620022#39620022 –

+0

你打算將其綁定到一個事件,像點擊或某事?或者在文件加載之後? –

回答

1

使用document.URL獲取當前url並獲得最後一個字正則表達式

var url = document.URL; 
 
var match = url.match(/([^/]*)$/); 
 

 
console.log(url); 
 
console.log(match); 
 

 
document.getElementById("username19").value = match[1];
<label for="username19" >Name</lable> 
 
<input name="username" id="username19" type="text" value="">

+0

感謝朋友,您非常樂於助人 –

1

你可能分裂使用substr它收到使用window.location.pathname然後在地址欄中當前路徑,最後用lastIndexOf('/')像拿到最後一部分:

var current_path_name = window.location.pathname 
console.log(current_path_name.substr(current_path_name.lastIndexOf('/') + 1)); 

希望這有助於。

1

你可以嘗試像爲 -

的JavaScript:

function ReplaceHash(){ 
    var url  = window.location.pathname;  /*URL without HASH*/ 
    var hash  = window.location.hash;   /*Only Hash URL*/ 
    var lastWord = hash.split('/'); 
    lastWord[(lastWord.length)-1] = 'username19'; /*Put your text here*/ 
    hash   = lastWord.join('/'); 
    url   = url + hash;     /*Your New URL*/ 
    return url; 
} 

var newUrl = ReplaceHash(); 
console.log(newUrl); 
0

加載輸入元素後加載。但是你可以將它綁定到一個事件。

$('input').load('input', function() { 
 
    var str = window.location.pathname.split("/");   
 
    var res = str[str.length-1]; 
 
    document.getElementById("username19").setAttribute("value", res); 
 
    console.log(res); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<label>Name</lable> 
 
<input name="username" id="username19" type="text" value="">