Javascript过滤前后空格
1. 循环检查
推荐 ☆☆☆
//供使用者调用
function trim(s){
return trimRight(trimLeft(s));
}
//去掉左边的空白
function trimLeft(s){
if(s == null) {
return "";
}
var whitespace = new String(" \t\n\r");
var str = new String(s);
if (whitespace.indexOf(str.charAt(0)) != -1) {
var j=0, i = str.length;
while (j < i && whitespace.indexOf(str.charAt(j)) != -1){
j++;
}
str = str.substring(j, i);
}
return str;
}
//去掉右边的空白
function trimRight(s){
if(s == null) return "";
var whitespace = new String(" \t\n\r");
var str = new String(s);
if (whitespace.indexOf(str.charAt(str.length-1)) != -1){
var i = str.length - 1;
while (i >= 0 && whitespace.indexOf(str.charAt(i)) != -1){
i--;
}
str = str.substring(0, i+1);
}
return str;
}
2. 正则表达式替换
推荐 ☆☆☆☆
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, "");
}
//去左空格;
function ltrim(s){
return s.replace(/(^\s*)/g, "");
}
//去右空格;
function rtrim(s){
return s.replace(/(\s*$)/g, "");
}
//去左右空格;
function trim(s){
return s.replace(/(^\s*)|(\s*$)/g, "");
}
3. JQuery
推荐 ☆☆☆☆☆
// 使用方法
$.trim(str)
// Jquery实现方法
function trim(str){
return str.replace(/^(\s|\u00A0)+/,'').replace(/(\s|\u00A0)+$/,'');
}
正文到此结束