javascript URL 编码与解码

编码与解码函数

编码函数

encodeURI
encodeURIComponent

解码函数

decodeURI
decodeURIComponent

编码规则相同点

会替换所有的字符,但不包括以下字符
非转义的字符:字母 数字 – _ . ! ~ * ‘ ( )

编码规则不同点

encodeURI 还会有一些不编码的字符,如下
保留字符:; , / ? : @ & = + $
数字符号:#

解码规则

解码只会解码对应规则编码出来的字符串,若不会解码出乱码。
encodeURI ->(对应) decodeURI
encodeURIComponent -> (对应) decodeURIComponent
这里的编码你可以用JavaScript自带的编码函数,当然你也可以按照规则和标准自行开发编码函数。

实战应用举例

说了这么多可能很多人就问了,JavaScript自带的编码与解码函数在实际中是如何应用的,为什么需要两个不同的编码与解码函数。
const url = "https://auto.3g.163.com/";

// 字符串编码
const params = {
  title: "今天去干什么?& 今天去哪里浪?",
  desc: "去哪里都行 & 哪里都不去!!!"
};

function compURL(url, params) {
  let result = encodeURI(url) + "?";
  for (let key in params) {
    result +=
      encodeURIComponent(key) + "=" + encodeURIComponent(params[key]) + "&";
  } //这样即使带有一些符号 ? & 等也可以方便的从url 中获取参数
  return result.slice(0, -1);
}

const urlCompd = compURL(url, params);

console.log(urlCompd);

// 字符窜解码获取数据

function parseURL(url) {
  const result = {
    sourceUrl: "",
    params: {}
  };
  result.sourceUrl = decodeURI(url.split("?")[0]);
  const paramStr = url.split("?")[1];
  const paramArr = paramStr.split("&");
  paramArr.forEach(item => {
    const itemArr = item.split("=");
    const key = decodeURIComponent(itemArr[0]),
      value = decodeURIComponent(itemArr[1]);
    result.params[key] = value;
  });
  return result;
}

const paramsData = parseURL(urlCompd);
console.log(paramsData);

在线代码

js判断输入字符串是否为空、空格、null的方法总结

判断字符串是否为空

1
2
3
4
5
var strings = '';
if (string.length == 0)
{
alert('不能为空');
}

判断字符串是否为“空”字符即用户输入了空格

1
2
3
4
5
var strings = ' ';
if (strings.replace(/(^s*)|(s*$)/g, "").length ==0)
{
alert('不能为空');
}

判断输入字符串是否为空或者全部都是空格?

1
2
3
4
5
6
function isNull( str ){
if ( str == "" ) return true;
var regu = "^[ ]+$";
var re = new RegExp(regu);
return re.test(str);
}

如果有null时上面代码就无法正常判断了,下面代码是判断为null的情况

1
2
3
4
5
var exp = null;
if (exp == null)
{
alert("is null");
}

exp 为 undefined 时,也会得到与 null 相同的结果,虽然 null 和 undefined 不一样。

注意:要同时判断 null 和 undefined 时可使用本法。 代码如下

1
2
3
4
5
var exp = null;
if (!exp)
{
alert("is null");
}

如果 exp 为 undefined,或数字零,或 false,也会得到与 null 相同的结果,虽然 null 和二者不一样。注意:要同时判断 null、undefined、数字零、false 时可使用本法。代码如下

1
2
3
4
5
var exp = null;
if (typeof exp == "null")
{
alert("is null");
}

为了向下兼容,exp 为 null 时,typeof null 总返回 object,所以不能这样判断。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<script type="text/javascript">
function testuser(){
var i= document.getElementByIdx_x("aa");
if (i.value=="null")
{
alert("请登录后再发表留言!")
return false;
}
else
{
alert(i.value)
return true;
}
}
</script>