从字符串的开头和结尾修剪空格 [英] Trim spaces from start and end of string

查看:169
本文介绍了从字符串的开头和结尾修剪空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图找到一种方法来从标题字符串的开头和结尾修剪空格。我正在使用它,但它似乎不起作用:

I am trying to find a way to trim spaces from the start and end of the title string. I was using this, but it doesn't seem to be working:

title = title.replace(/(^[\s]+|[\s]+$)/g, '');

任何想法?

推荐答案

注意:截至2015年,所有主流浏览器(包括IE> = 9)都支持String.prototype.trim()。这意味着对于大多数用例而言,只需执行 str.trim()就可以实现问题所要求的最佳方式。

Note: As of 2015, all major browsers (including IE>=9) support String.prototype.trim(). This means that for most use cases simply doing str.trim() is the best way of achieving what the question asks.

Steven Levithan在Javascript中分析了许多不同的 trim 实现性能条款。

Steven Levithan analyzed many different implementation of trim in Javascript in terms of performance.

他的推荐是:

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

用于快速跨浏览器的通用实现,以及

for "general-purpose implementation which is fast cross-browser", and

function trim11 (str) {
    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;
}

如果你想在所有浏览器中异常快速地处理长字符串。

"if you want to handle long strings exceptionally fast in all browsers".

  • blog.stevenlevithan.com -- Faster JavaScript Trim

这篇关于从字符串的开头和结尾修剪空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆