解决方法:
方法1:
使用jquery里面的全局函数$.trim()代替原生js方法trim():$.trim($("input[type='text']:eq(0)").val().trim());
方法2:
使用原生js来扩展String方法
1.写成类的方法:[ 调用格式: str.trim(); ]
代码如下 |
复制代码 |
<script type="text/javascript">
Function.prototype.method = function(name, func) {
this.prototype[name] = func;
return this;
};
if(String.prototype.trim){ //判断下浏览器是否自带有trim()方法
String.method('trim', function() {
return this.replace(/^s+|s+$/g, '');
});
String.method('ltrim', function() {
return this.replace(/^s+/g, '');
});
String.method('rtrim', function() {
return this.replace(/s+$/g, '');
});
}
</script>
|
例子
代码如下 |
复制代码 |
<input id="demo" type="" value=" 左右有空格 " /> <a href="javascript:;" onclick="test();">点击去除空格</a> <script type="text/javascript">
Function.prototype.method = function(name, func) {
this.prototype[name] = func;
return this;
};
if(!String.prototype.trim){ //判断下浏览器是否自带有trim()方法
String.method('trim', function() {
return this.replace(/^s+|s+$/g, '');
});
String.method('ltrim', function() {
return this.replace(/^s+/g, '');
});
String.method('rtrim', function() {
return this.replace(/s+$/g, '');
});
}
//测试调用方法: trim()
document.getElementById("demo").select();
var str=document.getElementById("demo").value;
function test(){
document.getElementById("demo").value=str.trim(); //可换成str.ltrim() 或 str.rtrim()
document.getElementById("demo").select();
}
</script>
|
解决方法二
写成函数:[ 调用格式: trim(str) ]
代码如下 |
复制代码 |
<script type="text/javascript">
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,"");
}
</script>
|
实例
代码如下 |
复制代码 |
<input id="demo" type="" value=" 左右有空格 " /> <a href="javascript:;" onclick="test();">点击去除空格</a> <script type="text/javascript">
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()
document.getElementById("demo").select();
var str=document.getElementById("demo").value;
function test(){
document.getElementById("demo").value=trim(str); //可换成str.ltrim() 或 str.rtrim()
document.getElementById("demo").select();
}
</script>
|
|