javascript的trim()函数的实现

  在JavaScript中我们需要用到trim的地方很多,但是JavaScript又没有独立的trim函数或者方法可以使用,所以我们需要自己写个trim函数来实现我们的目的

  比如方法一:

  String.prototype.trim= function(){

  // 用正则表达式将前后空格

  // 用空字符串替代。

  return this.replace(/(^\s*)|(\s*$)/g, "");

  }

  方法二:

  function trim(str){

  for(var i = 0 ; i

  for(var j =str.length; j>0 && str.charAt(j-1)==" " ; j--) ;

  if(i>j) return "";

  return str.substring(i,j);

  }

  Javascript中S.replace(/(^\s*)|(\s*$)/g, "");的 (^\s*)|(\s*$) 是什么意思的?

  首先是把/(^\s*)|(\s*$)/g 替换为""http://www.mlybyby.com

  然后,/.../g 里面的,是表示放置通配符的地方,g代表全局参数,(^\s*)或者(\s*$)都将被替换为""

  匹配首尾空白字符的正则表达式:^\s*|\s*$ 可以用来删除行首行尾的空白字符(包括空格、制表符、换页符等等),非常有用的表达式

  javascript内实现trim的方法

  直接拷贝的话,空格可能出现问题,请仔细检查

  function trim(str)

  {

  for(var i = 0 ; i

  for(var j =str.length; j>0 && str.charAt(j-1)==" " ; j--) ;

  if(i>j) return "";

  return str.substring(i,j);

  }

  方法二:

  // 增加一个名为 trim 的函数作为

  // String 构造函数的原型对象的一个方法。

  String.prototype.trim = function()

  {

  // 用正则表达式将前后空格

  // 用空字符串替代。

  return this.replace(/(^\s*)|(\s*$)/g, "");

  }

  // 有空格的字符串

  var s = " 我的长度 ";

  // 显示trim前长度

  window.alert(s + " trim前长度: (" + s.length + ")");

  // 删除前后空格

  s = s.trim();

  // 显示trim后长度

  window.alert(s + " trim后长度:(" + s.length + ")");

  方法3:

  //javascript中调用vbscript的函数,构造一个javascript版的trim 函数

  Javascript Trim Member Functions

  Use the code below to make trim a method of all Strings. These are useful to place in a global Javascript file included by all your pages.

  String.prototype.trim = function() {return this.replace(/^\s+|\s+$/g,"");}

  String.prototype.ltrim = function() {return this.replace(/^\s+/,"");}http://www.mlyrx120.com

  String.prototype.rtrim = function() {return this.replace(/\s+$/,"");}

  // example of using trim, ltrim, and rtrimvar myString = " hello my name is ";

  alert("*"+myString.trim()+"*");

  alert("*"+myString.ltrim()+"*");

  alert("*"+myString.rtrim()+"*");

  Javascript Trim Stand-Alone Functions

  If you prefer not to modify the string prototype, then you can use the stand-alone functions below.

  function trim(stringToTrim) {return stringToTrim.replace(/^\s+|\s+$/g,"");}

  function ltrim(stringToTrim) {return stringToTrim.replace(/^\s+/,"");}

  function rtrim(stringToTrim) {return stringToTrim.replace(/\s+$/,"");}

  // example of using trim, ltrim, and rtrimvar myString = " hello my name is ";

  alert("*"+trim(myString)+"*");

  alert("*"+ltrim(myString)+"*");

  alert("*"+rtrim(myString)+"*");

posted @ 2016-07-05 15:57  爱无边界  阅读(132)  评论(0)    收藏  举报