Appearance
判断一个字符串是否为空
备注
该方法默认会把 0
, null
,undefined
识别为空字符串,如果不想这样做,可以在第二个参数传入 true
来开启严格模式, 开启后传入非字符串类型的变量会报错。
语法
js
import { isStringEmpty } from 'warbler-js';
const result = isStringEmpty(str, strict);
参数
str
(String) : 目标字符串。?
strict
(Boolean) : 可选参数,默认为false
,是否开启严格模式,在严格模式下,只能传入字符串类型的参数,否则会报错。
返回值
Boolean : true
是空字符串, false
不是空字符串。
源码
js
const isStringEmpty = (str, strict = false) => {
const isString = Object.prototype.toString.call(str).split(' ')[1].replace(']', '') === 'String';
if (strict && !isString) {
throw new Error('isStringEmpty 方法需要传入字符串类型的参数');
}
return !str || str.trim().length === 0;
};
例子
js
import { isStringEmpty } from 'warbler-js';
// 默认模式下
console.log(isStringEmpty('')); //= > true
console.log(isStringEmpty('Hello')); //= > false
console.log(isStringEmpty(' ')); //= > true
console.log(isStringEmpty(0)); //= > true
console.log(isStringEmpty('0')); //= > false
console.log(isStringEmpty(null)); //= > true
console.log(isStringEmpty(undefined)); //= > true
// 严格模式下
console.log(isStringEmpty('', true)); //= > true
console.log(isStringEmpty('Hello', true)); //= > false
console.log(isStringEmpty(' ', true)); //= > true
console.log(isStringEmpty(0, true)); //= > 报错
console.log(isStringEmpty('0', true)); //= > false
console.log(isStringEmpty(null, true)); //= > 报错
console.log(isStringEmpty(undefined, true)); //= > 报错
添加版本
1.2.1