js编写trim()函数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/devincob/article/details/81984636
代码如下:

<script language="javascript"> 
    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,""); 
} 

//写成函数可以这样:(trim(str)) 

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> 

猜你喜欢

转载自blog.csdn.net/devincob/article/details/81984636