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

作者:jingxian 时间:2024-04-19 09:56:56 

判断字符串是否为空


var strings = '';
if (string.length == 0)
{
alert('不能为空');
}

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


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

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


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

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


var exp = null;
if (exp == null)
{
alert("is null");
}

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

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


var exp = null;
if (!exp)
{
alert("is null");
}

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


var exp = null;
if (typeof exp == "null")
{
alert("is null");
}

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


<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>

标签:js,判断,字符串,null
0
投稿

猜你喜欢

  • MySQL中两种快速创建空表的方式的区别

    2008-12-17 14:34:00
  • MYSQL大表加索引的实现

    2024-01-16 03:12:36
  • python机器学习包mlxtend的安装和配置详解

    2021-11-09 22:53:06
  • Python实现读取SQLServer数据并插入到MongoDB数据库的方法示例

    2022-11-16 04:14:21
  • python time()的实例用法

    2022-01-09 02:33:02
  • 用Python Turtle画棵樱花树送给自己

    2022-06-30 10:16:47
  • 解析MySQL数据库性能优化的六大技巧

    2024-01-13 02:18:49
  • javascript图片预加载

    2009-08-30 12:47:00
  • sqlserver和oracle中对datetime进行条件查询的一点区别小结

    2024-01-15 16:25:54
  • js实现文字列表无缝滚动效果

    2024-04-19 10:16:12
  • vue 使用饿了么UI仿写teambition的筛选功能

    2024-04-27 16:05:09
  • Python Tkinter基础控件用法

    2023-04-11 18:35:14
  • 同时安装sql2000和sql2005,经验点滴

    2008-03-04 17:56:00
  • 深入理解Python单元测试unittest的使用示例

    2022-03-18 04:51:00
  • python中使用docx模块处理word文档

    2023-04-07 18:50:44
  • javascript开发随笔一 preventDefault的必要

    2024-04-26 17:14:05
  • 删除SVN三种方法delSvn(windows+linux)

    2023-02-06 17:06:41
  • Win7环境下搭建Go开发环境(基于VSCode编辑器)

    2024-04-30 09:59:04
  • mysql4.1以上版本连接时出现Client does not support authentication protocol问题解决办法

    2023-11-18 06:10:15
  • Python PyInstaller库基本使用方法分析

    2022-03-19 16:29:46
  • asp之家 网络编程 m.aspxhome.com