如何修剪()字符串中的空格?

发布于 2024-12-01 11:54:12 字数 78 浏览 1 评论 0原文

JavaScript 似乎没有原生 trim() 方法。如何使用 JavaScript 修剪字符串开头和结尾的空格?

JavaScript doesn't seem to have a native trim() method. How can I trim white spaces at the start and end of a string with JavaScript?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(19

顾挽 2024-12-08 11:54:12

jQuery 的最短形式:

string = $.trim(string);

链接

The shortest form for jQuery:

string = $.trim(string);

Link

濫情▎り 2024-12-08 11:54:12

根据此页面,最好的全能方法是

return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');

当然,如​​果您使用jQuery ,它将为您提供优化的修剪方法。

according to this page the best all-around approach is

return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');

Of course if you are using jQuery , it will provide you with an optimized trim method.

沙与沫 2024-12-08 11:54:12

我知道这个问题很古老,但现在,Javascript 实际上确实有一个原生的 .trim()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim

I know this question is ancient but now, Javascript actually does have a native .trim()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim

夕色琉璃 2024-12-08 11:54:12

嗯,正如很多人总是说的那样,trim 功能运行得很好,但是如果您不想使用整个框架来执行修剪,那么查看它的实现可能会很有用。与这里

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

已经提出的其他解决方案相比,我在此实现中看到的主要优点是:

  • 'g' 标志允许您对多行字符串执行修剪
  • (text || "") 语法确保函数始终有效,即使传递的参数为 null 或未定义。

Well, as a lot of people always says, the trim function works pretty well, but if you don't want to use a whole framework just to perform a trim, it may be useful to take a look at its implementation. So here it is:

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

The main advantages I see in this implementation, comparing to other solution already proposed here are:

  • The 'g' flag that allows you to perfom a trim on a multi-line string
  • The (text || "") syntax that ensure that the function will always work, even if the argument passed is null or undefined.
风启觞 2024-12-08 11:54:12

正如其他几个人已经指出的那样,通常最好使用第三方 JS 库来完成此类操作。并不是说 trim() 是一个需要您自己构建的复杂函数,而是有很多非 JavaScript 原生函数需要您自己编写,因此使用库很快就会变得更具成本效益。

当然,使用 JS 库的另一个优点是,作者付出了艰苦的工作来确保这些功能可以在所有主要浏览器上运行,这样您就可以编写标准接口,而忘记 Internet Explorer 和所有浏览器之间令人恼火的差异。其他浏览器。

As a couple of others have already noted, it's usually best to do this sort of thing by using a third-party JS library. Not that trim() is a complicated function to build yourself, but there are so many functions that aren't native to JavaScript that you might need and end-up writing yourself, it soon becomes more cost-effective to use a library.

Of course, another advantage of using a JS library is that the authors do the hard work of ensuring that the functions work across all the major browsers, so that you can code to a standard interface and forget about the irritating differences between Internet Explorer and all the other browsers.

尬尬 2024-12-08 11:54:12

@Pat 的稍微小一点的版本。

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

A slightly tinier version of @Pat's.

return str.replace( /^\s+|\s+$/g, '' );
如歌彻婉言 2024-12-08 11:54:12

对于 ltrim,将字符串开头的空格替换为空:

str2 = str.replace(/^\s+/,'');

对于 rtrim,将字符串末尾的空格替换为空:

str2 = str.replace(/\s+$/,'');

对于 trim:

str2 = str.replace(/^\s+|\s+$/g,'');

这些都使用正则表达式来完成实际工作。

For ltrim, replace spaces anchored at the start of the string with nothing:

str2 = str.replace(/^\s+/,'');

For rtrim, replace spaces anchored at the end of the string with nothing:

str2 = str.replace(/\s+$/,'');

For trim:

str2 = str.replace(/^\s+|\s+$/g,'');

These all use regex'es to do the actual work.

预谋 2024-12-08 11:54:12

为什么不直接修改 String 原型呢?为什么不从开源库中窃取修剪功能,就像我在 YUI 中所做的那样? (你真的需要加载整个框架来完成这个简单的任务吗?)将它们放在一起,你会得到这个:

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

var s = " hello ";
alert(s.trim() == "hello"); // displays true

Why not just modify the String prototype? Why not steal the trim function from an open source library, like I did here with YUI? (Do you really need to load and entire framework for this simple taks?) Put them together and you get this:

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

var s = " hello ";
alert(s.trim() == "hello"); // displays true
﹎☆浅夏丿初晴 2024-12-08 11:54:12

使用 Ariel Flesler 的快速修剪功能

// Licensed under BSD
function myBestTrim( str ){
 var start = -1,
  end = str.length;
 while( str.charCodeAt(--end) < 33 );
 while( str.charCodeAt(++start) < 33 );
 return str.slice( start, end + 1 );
};

我的解决方案不过,会是这样的(因为 Firefox 3.5 及更高版本中的 String 对象已经有一个 trim 方法):

String.prototype.trim = String.prototype.trim || function () {
    var start = -1,
        end   = this.length;

    while( this.charCodeAt(--end) < 33 );
    while( this.charCodeAt(++start) < 33 );

    return this.slice( start, end + 1 );
};

Use Ariel Flesler's fast trim function:

// Licensed under BSD
function myBestTrim( str ){
 var start = -1,
  end = str.length;
 while( str.charCodeAt(--end) < 33 );
 while( str.charCodeAt(++start) < 33 );
 return str.slice( start, end + 1 );
};

My solution, though, would be this (because the String object in Firefox 3.5 and above already has a trim method):

String.prototype.trim = String.prototype.trim || function () {
    var start = -1,
        end   = this.length;

    while( this.charCodeAt(--end) < 33 );
    while( this.charCodeAt(++start) < 33 );

    return this.slice( start, end + 1 );
};
梦萦几度 2024-12-08 11:54:12

我考虑了一个修剪功能速度。该函数明显击败了所有 24 个竞争对手(其中许多使用正则表达式)以及 Chrome 和 Chromium(!) 的原生 string.trim(),并且执行速度与 Safari 的 trim() 一样快。测试结果在这里:http://jsperf.com/mega-trim-test/7

function trim27(str) {
  var c;
  for (var i = 0; i < str.length; i++) {
    c = str.charCodeAt(i);
    if (c == 32 || c == 10 || c == 13 || c == 9 || c == 12)
    continue; else break;
  }
  for (var j = str.length - 1; j >= i; j--) {
    c = str.charCodeAt(j);
    if (c == 32 || c == 10 || c == 13 || c == 9 || c == 12)
    continue; else break;
  }
  return str.substring(i, j + 1);
}

该函数会修剪字符“\n\r\t\f”,但很容易添加更多空白字符,例如。正则表达式用作空格 (\s) 的那些仅会造成轻微性能损失(请参阅 http:// jsperf.com/mega-trim-test/8)。

编辑:前面的trim27()仅修剪最常见的字符(“\n\r\t\f”),但为了修剪所有可能的空白,我在下面添加了一个新函数mytrim():

if (!String.prototype.trim || "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF".trim() || navigator.userAgent.toString().toLowerCase().indexOf("chrome") != -1)
    var mytrim = function(str) {
        var c;
        for (var i = 0; i < str.length; i++) {
            c = str.charCodeAt(i);
            if (c == 32 || c == 10 || c == 13 || c == 9 || c == 12 || c == 11 || c == 160 || c == 5760 || c == 6158 || c == 8192 || c == 8193 || c == 8194 || c == 8195 || c == 8196 || c == 8197 || c == 8198 || c == 8199 || c == 8200 || c == 8201 || c == 8202 || c == 8232 || c == 8233 || c == 8239 || c == 8287 || c == 12288 || c == 65279)
            continue; else break;
        }
        for (var j = str.length - 1; j >= i; j--) {
            c = str.charCodeAt(j);
            if (c == 32 || c == 10 || c == 13 || c == 9 || c == 12 || c == 11 || c == 160 || c == 5760 || c == 6158 || c == 8192 || c == 8193 || c == 8194 || c == 8195 || c == 8196 || c == 8197 || c == 8198 || c == 8199 || c == 8200 || c == 8201 || c == 8202 || c == 8232 || c == 8233 || c == 8239 || c == 8287 || c == 12288 || c == 65279)
            continue; else break;
        }
        return str.substring(i, j + 1);
    };
    else var mytrim = function(str) {
        return str.trim();
    }

这样使用它:

var foo = mytrim(" \n \t Trimmed \f \n "); // foo is now "Trimmed"

上面mytrim() 执行以下操作:

I made a trim-function speed in mind. This function beats in a clear difference all of 24 competitors (of which many use regular expressions) and also native string.trim() of Chrome and Chromium(!) and performs as speedy as Safari's trim(). Test results are here: http://jsperf.com/mega-trim-test/7

function trim27(str) {
  var c;
  for (var i = 0; i < str.length; i++) {
    c = str.charCodeAt(i);
    if (c == 32 || c == 10 || c == 13 || c == 9 || c == 12)
    continue; else break;
  }
  for (var j = str.length - 1; j >= i; j--) {
    c = str.charCodeAt(j);
    if (c == 32 || c == 10 || c == 13 || c == 9 || c == 12)
    continue; else break;
  }
  return str.substring(i, j + 1);
}

The function trims characters " \n\r\t\f", but it's easy to add more whitespace-characters, eg. those that regexp uses as whitespaces (\s) with only a minor performance lost ( please see http://jsperf.com/mega-trim-test/8 ).

Edit: The previous trim27() trims only the most common characters (" \n\r\t\f"), but to trim all possible whitespaces, I included below a new function mytrim():

if (!String.prototype.trim || "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF".trim() || navigator.userAgent.toString().toLowerCase().indexOf("chrome") != -1)
    var mytrim = function(str) {
        var c;
        for (var i = 0; i < str.length; i++) {
            c = str.charCodeAt(i);
            if (c == 32 || c == 10 || c == 13 || c == 9 || c == 12 || c == 11 || c == 160 || c == 5760 || c == 6158 || c == 8192 || c == 8193 || c == 8194 || c == 8195 || c == 8196 || c == 8197 || c == 8198 || c == 8199 || c == 8200 || c == 8201 || c == 8202 || c == 8232 || c == 8233 || c == 8239 || c == 8287 || c == 12288 || c == 65279)
            continue; else break;
        }
        for (var j = str.length - 1; j >= i; j--) {
            c = str.charCodeAt(j);
            if (c == 32 || c == 10 || c == 13 || c == 9 || c == 12 || c == 11 || c == 160 || c == 5760 || c == 6158 || c == 8192 || c == 8193 || c == 8194 || c == 8195 || c == 8196 || c == 8197 || c == 8198 || c == 8199 || c == 8200 || c == 8201 || c == 8202 || c == 8232 || c == 8233 || c == 8239 || c == 8287 || c == 12288 || c == 65279)
            continue; else break;
        }
        return str.substring(i, j + 1);
    };
    else var mytrim = function(str) {
        return str.trim();
    }

Use it this way:

var foo = mytrim(" \n \t Trimmed \f \n "); // foo is now "Trimmed"

The above mytrim() does the following:

  • Trims 26 different whitespaces (all of 25 whitespaces mentioned in http://perfectionkills.com/whitespace-deviations/ and additionally uFEFF, which is ZERO WIDTH NO-BREAK SPACE.
  • Makes trimming results consistent across browsers.
  • Uses native trim() if it is available AND has ability to trim all of 27 different whitespaces. The exception is Chrome and Chromium which both have so slow native trim() that instead of native we use our custom trim.
  • AND THE MOST IMPORTANT: Is not beautiful and is not short, but IS CLEARLY FASTER than any of the 24 competitive alternatives in http://jsperf.com/mega-trim-test/12 (exception: rather old Firefox 3.6.25 in Windows 7 runs mytrim() rather slowly for unknown reason).
昔梦 2024-12-08 11:54:12

我将其与本机 JavaScript 一起使用

// Adding trim function to String object if its not there
if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, '');
  }
}

,如下所示

var myString = "                  some text                  ";

alert(myString.trim());

示例

// Adding trim function to String object if its not there
if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, '');
  }
}

var str = "      some text              ";
console.log(str.trim());

I use this with native JavaScript

// Adding trim function to String object if its not there
if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, '');
  }
}

Use like this

var myString = "                  some text                  ";

alert(myString.trim());

Example

// Adding trim function to String object if its not there
if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, '');
  }
}

var str = "      some text              ";
console.log(str.trim());

多像笑话 2024-12-08 11:54:12

许多 JavaScript 问题的答案:jQuery

$j.trim(string)

注意:上面假设您的 jQuery 已设置为:

<script type="text/javascript">$j = jQuery.noConflict();</script>

这比“$”更明智,并且比每次键入“jQuery”简洁得多。

The answer to so many JavaScript questions: jQuery

$j.trim(string)

Note: the above assumes your jQuery has been setup with:

<script type="text/javascript">$j = jQuery.noConflict();</script>

Which is far more sensible than "$", and far less verbose than typing "jQuery" every time.

北凤男飞 2024-12-08 11:54:12

Microsoft .NET 还具有 String.trim 函数作为 JavaScript 的一部分基本类型扩展。如果您正在编写 ASP.NET 应用程序,则可以使用它。

Microsoft .NET also has String.trim function as a part of JavaScript Base Type Extensions. It could be used if you are coding ASP.NET application.

十年九夏 2024-12-08 11:54:12

我用这个。

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

I use this.

    String.prototype.trim = function() {
        return this.replace(/^\s+|\s+$/g,"");
    }
只为一人 2024-12-08 11:54:12

实际上,对于 jQuery,这似乎是这样的:

jQuery.trim(string)

(Reference)

Actually, with jQuery this seems to be the way:

jQuery.trim(string)

(Reference)

窝囊感情。 2024-12-08 11:54:12

我用这个:

使用函数。

 function trim($) { 
                return (typeof $ == "function" ? $() : $).replace(/[\s]*/g,"")
        }

        code example: 

        trim((function(){ return "a  b"})) // ab

        trim(" a  b") //ab

I use this:

Work with functions.

 function trim($) { 
                return (typeof $ == "function" ? $() : $).replace(/[\s]*/g,"")
        }

        code example: 

        trim((function(){ return "a  b"})) // ab

        trim(" a  b") //ab
不羁少年 2024-12-08 11:54:12

这可能不是最快的,并且可能违反“.trim()”可能真正应该是什么,但我不喜欢正则表达式(主要是因为它需要很多时间来弄清楚它们的真正含义/作用)并且我喜欢拥有一些我知道的东西无论我是否有 jQuery 都可以工作(更不用说正确的版本,因为我尝试了 $.trim(myVar) 与 jQuery 1.4.2 并且它不起作用),并且将摆脱所有多余的空格,不就在最后,按照应有的方式重建它:

function Trim(obj) {
    var coll = "";
    var arrObj = obj.split(' ');

    for (var i=0;i<arrObj.length;i++) {
        if (arrObj[i] == "") {
            arrObj.splice(i,1);  // removes array indices containing spaces
        }
    }
    //alert(arrObj.length);  // should be equal to the number of words
    // Rebuilds with spaces in-between words, but without spaces at the end
    for (var i=0;i<arrObj.length;i++) {
        if (arrObj[i] != "" && i != arrObj.length-1)
            coll += arrObj[i] + " ";
        if (arrObj[i] != "" && i == arrObj.length-1)
            coll += arrObj[i];
    }

    return coll;
}

This is probably not the fastest, and might violate what ".trim()" probably should really be, but I don't like RegExs (mainly because it takes so much time to figure out what they really mean/do) and I like having something that I know will work regardless of whether I have jQuery or not (not to mention the right version, since I tried $.trim(myVar) with jQuery 1.4.2 and it does not work), and will get rid of ALL extra spaces, not just at the end, rebuilding it like it should be:

function Trim(obj) {
    var coll = "";
    var arrObj = obj.split(' ');

    for (var i=0;i<arrObj.length;i++) {
        if (arrObj[i] == "") {
            arrObj.splice(i,1);  // removes array indices containing spaces
        }
    }
    //alert(arrObj.length);  // should be equal to the number of words
    // Rebuilds with spaces in-between words, but without spaces at the end
    for (var i=0;i<arrObj.length;i++) {
        if (arrObj[i] != "" && i != arrObj.length-1)
            coll += arrObj[i] + " ";
        if (arrObj[i] != "" && i == arrObj.length-1)
            coll += arrObj[i];
    }

    return coll;
}
浊酒尽余欢 2024-12-08 11:54:12

这是一个老问题,但这些都不适合我。我只需要修剪前导和尾随空白,这就是我所做的。我的 div 标签有一个 id = start-date。

$("#start-date").text().trim()

This is an old question but none of these worked for me. I just needed to trim leading and trailing white space and this is what I did. My div tag had an id = start-date.

$("#start-date").text().trim()
空‖城人不在 2024-12-08 11:54:12

您可以使用以下...

function trim(str) {
    try {
        if (str && typeof(str) == 'string') {
            return str.replace(/^\s*|\s*$/g, "");
        } else {
            return '';
        }
    } catch (e) {
        return str;
    }
}

You can use following ...

function trim(str) {
    try {
        if (str && typeof(str) == 'string') {
            return str.replace(/^\s*|\s*$/g, "");
        } else {
            return '';
        }
    } catch (e) {
        return str;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文