js关于处理字符串中的空格问题方法总结

JavaScript011

js关于处理字符串中的空格问题方法总结,第1张

一、函数

 

function trim(str){ //删除左右两端的空格

return str.replace(/(^\s )|(\s $)/g, "")

}

function ltrim(str){ //删除左边的空格

return str.replace(/(^\s*)/g,"")

}

function rtrim(str){ //删除右边的空格

return str.replace(/(\s*$)/g,"")

}

函数调用 trim(str)

二、js对象的方法

String.prototype.trim=function(){

return this.replace(/(^\s )|(\s $)/g, "")

}

String.prototype.ltrim=function(){

return this.replace(/(^\s*)/g,"")

}

String.prototype.rtrim=function(){

return this.replace(/(\s*$)/g,"")

}

类中方法调用 str.trim()

三、将公共方法提取到一个或多个公共js文件,需要的时候直接引用;

//判断字符是否为空的方法

isEmpty(obj){

var regu = "^[ ]+$"

var re = new RegExp(regu)

if(typeof obj == "undefined" || obj == null || obj == "" || re.test(obj)){

return true

}else{

return false

}

},

用法:

if(this.isEmpty(this.keyword)){

console.log('空字符')

}