2017-10-17 51 views
0

您好,我在我的網站上有一個輸入字段,用戶可以輸入搜索字詞。使用js或jQuery將強制空格轉換爲HTML輸入字段的%20

我將用戶輸入的值並吐出到一個url字符串。

jQuery("#searchButton").click(function(){ 
 
    var simpleSearchTermLocal = jQuery('#searchField').val(); 
 
    var urlString = "www.mysite.com/" + simpleSearchTermLocal; 
 
    alert(urlString); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" id="searchField" /> 
 
<button id="searchButton">search</button>

因此,當有人輸入類似「ABC」在搜索字段中,變量urlString的值變爲www.mysite.com/ABC這是罰款。

但是當在輸入字段中輸入空格時,如「ABC 123」,urlString變成www.mysite.com/ABC 123這沒有問題。我想變成www.mysite.com/ABC%20123

有什麼建議嗎?

感謝

回答

2

你想要encodeURI()功能。

var theString = "The quick brown fox jumped over the lazy dog."; 
 

 
console.log(encodeURI(theString));

+0

真棒這就是答案,謝謝! –