js如何判断字符串是否为空


本文摘自PHP中文网,作者coldplay.xixi,侵删。

js判断字符串是否为空的方法:1、判断字符串是否为空,代码为【if (string.length == 0)】;2、判断字符串是否为“空”字符即用户输入了空格,代码为【if (strings.replace(/(^s*)|(s*$)..】。

本教程操作环境:windows7系统、javascript1.8.5版,DELL G3电脑,该方法适用于所有品牌电脑。

js判断字符串是否为空的方法:

判断字符串是否为空

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>

相关免费学习推荐:javascript视频教程

以上就是js如何判断字符串是否为空的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

javascript中this的用法是什么

javascript中怎么求数组的平均值

storage event如何实现页面间通信

javascript主要有哪些数据类型

javascript怎么执行cmd命令

通过代码示例,了解css3+javascript按钮水波纹效果

学习在 javascript 中正确处理变量

如何定义一个javascript函数

javascript如何修改html

在html文档中嵌入javascript的四种方法

更多相关阅读请进入《javascript》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...