javascript trim implementation with regexp

there is some research by Steven Levithan, who ventured to find various kind of way to implement the code that do string trimming. 

 

 

he published his algorithms on this link:

 

http://blog.stevenlevithan.com/archives/faster-trim-javascript

 

 

Below shows some of the implementaiton that uses regular expression to do the trimming.

 

/**************************************
*@Summary
*  various kind of the string.trim method 
*
* 
* @Usage:
*   
* compress( "foo=1&foo=2&blah=a&blah=b&foo=3" ) == "foo=1,2,3&blah=a,b"
*
* @TODO:
* some more practical use of the string.replac method call 
*  assert("a b c".replace(/a/, function() { return ""; } ) == " b c", "returning an empty result removes a match");
***************************************/

function trim1(str) {
  return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

function trim2(str) {
  return str.replace(/^\s+|\s+$/g, '');
}

function trim(str) {
  var str = str.replace(/^\s\s*/, ''), 
    ws = /\s/, i = str.length;
  while (ws.test(str.charAt(--i)));
  return s.splice(0, i + 1);
}

 

there is no reason to do more than one impl if none has competitive advantage over another. below shows a table that compare the performance on different use cases. 

 

 

         Selector  Trim| Document Trim

Trim1 8.7                    2075.8

Trim2 8.5                    3706.7

trim 13.8                    169.4

你可能感兴趣的:(JavaScript)