search
HomeWeb Front-endJS TutorialJavaScript去掉空格的方法集合_javascript技巧

实现1

复制代码 代码如下:

String.prototype.trim = function () {
return this .replace(/^\s\s*/, '' ).replace(/\s\s*$/, '' );
}

看起来不怎么样,动用了两次正则替换,实际速度非常惊人,主要得益于浏览器的内部优化。一个著名的例子字符串拼接,直接相加比用Array做成的StringBuffer还快。base2类库使用这种实现。
实现2
复制代码 代码如下:

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

和实现1很相似,但稍慢一点,主要原因是它最先是假设至少存在一个空白符。Prototype.js使用这种实现,不过其名字为strip,因为Prototype的方法都是力求与Ruby同名。
实现3
复制代码 代码如下:

String.prototype.trim = function () {
return this .substring(Math.max( this .search(/\S/), 0), this .search(/\S\s*$/) + 1);
}

以截取方式取得空白部分(当然允许中间存在空白符),总共调用了四个原生方法。设计得非常巧妙,substring以两个数字作为参数。Math.max以两个数字作参数,search则返回一个数字。速度比上面两个慢一点,但比下面大多数都快。
实现4
复制代码 代码如下:

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

这个可以称得上实现2的简化版,就是利用候选操作符连接两个正则。但这样做就失去了浏览器优化的机会,比不上实现3。由于看来很优雅,许多类库都使用它,如JQuery与mootools
实现5
复制代码 代码如下:

String.prototype.trim = function () {
var str = this ;
str = str.match(/\S+(?:\s+\S+)*/);
return str ? str[0] : '' ;
}

match是返回一个数组,因此原字符串符合要求的部分就成为它的元素。为了防止字符串中间的空白符被排除,我们需要动用到非捕获性分组(?:exp)。由于数组可能为空,我们在后面还要做进一步的判定。好像浏览器在处理分组上比较无力,一个字慢。所以不要迷信正则,虽然它基本上是万能的。
实现6
复制代码 代码如下:

String.prototype.trim = function () {
return this .replace(/^\s*(\S*(\s+\S+)*)\s*$/, '$1' );
}

把符合要求的部分提供出来,放到一个空字符串中。不过效率很差,尤其是在IE6中。
实现7
复制代码 代码如下:

String.prototype.trim = function () {
return this .replace(/^\s*(\S*(?:\s+\S+)*)\s*$/, '$1' );
}

和实现6很相似,但用了非捕获分组进行了优点,性能效之有一点点提升。
实现8
复制代码 代码如下:

String.prototype.trim = function () {
return this .replace(/^\s*((?:[\S\s]*\S)?)\s*$/, '$1' );
}

沿着上面两个的思路进行改进,动用了非捕获分组与字符集合,用?顶替了*,效果非常惊人。尤其在IE6中,可以用疯狂来形容这次性能的提升,直接秒杀火狐。
实现9
复制代码 代码如下:

String.prototype.trim = function () {
return this .replace(/^\s*([\S\s]*?)\s*$/, '$1' );
}

这次是用懒惰匹配顶替非捕获分组,在火狐中得到改善,IE没有上次那么疯狂。
实现10
复制代码 代码如下:

String.prototype.trim = function () {
var str = this ,
whitespace = ' \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000' ;
for ( var i = 0,len = str.length; i if (whitespace.indexOf(str.charAt(i)) === -1) {
str = str.substring(i);
break ;
}
}
for (i = str.length - 1; i >= 0; i--) {
if (whitespace.indexOf(str.charAt(i)) === -1) {
str = str.substring(0, i + 1);
break ;
}
}
return whitespace.indexOf(str.charAt(0)) === -1 ? str : '' ;
}

我只想说,搞出这个的人已经不是用牛来形容,已是神一样的级别。它先是把可能的空白符全部列出来,在第一次遍历中砍掉前面的空白,第二次砍掉后面的空白。全过程只用了indexOf与substring这个专门为处理字符串而生的原生方法,没有使用到正则。速度快得惊人,估计直逼上内部的二进制实现,并且在IE与火狐(其他浏览器当然也毫无疑问)都有良好的表现。速度都是零毫秒级别的。
实现11
复制代码 代码如下:

String.prototype.trim = function () {
var str = this ,
str = str.replace(/^\s+/, '' );
for ( var i = str.length - 1; i >= 0; i--) {
if (/\S/.test(str.charAt(i))) {
str = str.substring(0, i + 1);
break ;
}
}
return str;
}

实现10已经告诉我们普通的原生字符串截取方法是远胜于正则替换,虽然是复杂一点。但只要正则不过于复杂,我们就可以利用浏览器对正则的优化,改善程序执行效率,如实现8在IE的表现。我想通常不会有人在项目中应用实现10,因为那个whitespace 实现太长太难记了(当然如果你在打造一个类库,它绝对是首先)。实现11可谓其改进版,前面部分的空白由正则替换负责砍掉,后面用原生方法处理,效果不逊于原版,但速度都是非常逆天。
实现12
复制代码 代码如下:

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

实现10与实现11在写法上更好的改进版,注意说的不是性能速度,而是易记与使用上。和它的两个前辈都是零毫秒级别的,以后就用这个来工作与吓人。
下面是老外给出的比较结果,执行背景是对Magna Carta 这文章(超过27,600字符)进行trim操作。
实现 Firefox 2 IE 6
trim1 15ms trim2 31ms trim3 46ms 31ms
trim4 47ms 46ms
trim5 156ms 1656ms
trim6 172ms 2406ms
trim7 172ms 1640ms
trim8 281ms trim9 125ms 78ms
trim10 trim11 trim12
复制代码 代码如下:

//String.prototype使用
//批量替换,比如:str.ReplaceAll([/a/g,/b/g,/c/g],["aaa","bbb","ccc"])
String.prototype.ReplaceAll=function (A,B) {
var C=this;
for(var i=0;iC=C.replace(A[i],B[i]);
};
return C;
};
// 去掉字符两端的空白字符
String.prototype.Trim=function () {
return this.replace(/(^[\t\n\r]*)|([\t\n\r]*$)/g,'');
};
// 去掉字符左边的空白字符
String.prototype.LTrim=function () {
return this.replace(/^[\t\n\r]/g,'');
};
// 去掉字符右边的空白字符
String.prototype.RTrim=function () {
return this.replace(/[\t\n\r]*$/g,'');
};
// 返回字符的长度,一个中文算2个
String.prototype.ChineseLength=function()
{
return this.replace(/[^\x00-\xff]/g,"**").length;
};
// 判断字符串是否以指定的字符串结束
String.prototype.EndsWith=function (A,B) {
var C=this.length;
var D=A.length;
if(D>C)return false;
if(B) {
var E=new RegExp(A+'$','i');
return E.test(this);
}else return (D==0||this.substr(C-D,D)==A);
};
// 判断字符串是否以指定的字符串开始
String.prototype.StartsWith = function(str)
{
return this.substr(0, str.length) == str;
};
// 字符串从哪开始多长字符去掉
String.prototype.Remove=function (A,B) {
var s='';
if(A>0)s=this.substring(0,A);
if(A+Breturn s;
};
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool