ITeye博客

javascript trim方法

harbey · 2009-04-24 10:44 · javascript · Markdown

在javascript中的string对象没有trim方法,所以trim功能需要自己实现: 代码如下:

﹤scriptlanguage=”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,'');
}
﹤/script﹥

使用如下

﹤scripttype=”text/javascript”﹥
  alert(document.getElementById(’abc’).value.trim());
  alert(document.getElementById(’abc’).value.ltrim());
  alert(document.getElementById(’abc’).value.rtrim());
﹤/script﹥

评论(1)

  1. #1 楼 · lseeo · 2009-04-26 09:49

    In ltrim and rtrim functions, your regex pattern is strange."/(^s*)/g, /(s*$)/g".

评论功能维护中,当前仅展示历史评论。