encodeURI() 函数可把字符串作为 URI 进行编码。
decodeURI() 函数可对 encodeURI() 函数编码过的 URI 进行解码。
在日常url字符拼接中经常用到,下面是一个小的案例
html代码
<div class=“demo”>
<h2>DEMO1</h2>
<label for="">你的搜索关键词:</label><input type=“text” value="" “check1(this)”/><br>
<label for="">网址处理:</label><input type=“text” value="" “check1(this)”/><br>
<label for="">结果:</label><input type=“text” disabled/>
</div>
js代码
function check1(self){
var div = document.getElementsByClassName(“demo”)[0];
var output = div.getElementsByTagName(“input”)[2];
var input = self.value;
var str = input.substr(0 , 4);
if(str != “http”){
output.value = “http://www.baidu.com/s?oq=” + encodeURI(self.value);;
}else{
for(var i = 0 ; i < input.length ; i++){
var temp = input.substring(i-3 , i);
if(temp == “oq=”){
temp = input.substring(i , input.length);
break;
}
}
output.value = "你搜索的关键词为 : " + decodeURI(temp);
}
}