JavaScript去除空格

2012-01-14 14:16:13|?次阅读|上传:wustguangh【已有?条评论】发表评论

关键词:JavaScript, 字符处理|来源:唯设编程网

1.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, "");
}

2.全文匹配替换

var regExp = new RegExp("需要被替换的字符',"g")
var text = "…………";
text = text.replace(regExp , "替换的字符");
3.方案
String .prototype.trim = function(){
   var matches = this.match(/^[ 	

]+/);
   var prefixLength = (matches == null) ? 0:matches[0].length;
   matches = this.match(/[ 	
]+$/);
   var suffixLength = (matches == null) ? 0:matches[0].length;
   return this.slice(prefixLength,this.length-suffixLength);
}
4.使用正则表达式(推荐):
function strTrim(str) {
	return str.replace(/(^s*)|(s*$)/g, "");
};

 

发表评论0条 】
网友评论(共?条评论)..
JavaScript去除空格