javascript trim implementation with regexp

本文介绍了由Steven Levithan提出的几种JavaScript字符串修剪方法及其性能对比。这些方法使用正则表达式来去除字符串首尾的空白字符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值