简体   繁体   English

从字符串的开头和结尾修剪空格

[英]Trim spaces from start and end of string

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, '');

Any ideas?有任何想法吗?

Note: As of 2015, all major browsers (including IE>=9) support String.prototype.trim() .注意:截至 2015 年, 所有主流浏览器(包括 IE>=9)都支持 String.prototype.trim() This means that for most use cases simply doing str.trim() is the best way of achieving what the question asks.这意味着对于大多数用例,简单地执行str.trim()是实现问题的最佳方式。


Steven Levithan analyzed many different implementation of trim in Javascript in terms of performance. Steven Levithan 从性能方面分析了 Javascript 中trim许多不同实现。

His recommendation is:他的建议是:

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". “如果你想在所有浏览器中以异常快的速度处理长字符串”。

References参考

If using jQuery is an option:如果使用 jQuery 是一种选择:

/**
 * Trim the site input[type=text] fields globally by removing any whitespace from the
 * beginning and end of a string on input .blur()
 */
$('input[type=text]').blur(function(){
    $(this).val($.trim($(this).val()));
});

or simply:或者干脆:

$.trim(string);

As @ChaosPandion mentioned, the String.prototype.trim method has been introduced into the ECMAScript 5th Edition Specification, some implementations already include this method, so the best way is to detect the native implementation and declare it only if it's not available:正如@ChaosPandion提到的, String.prototype.trim方法已经被引入到ECMAScript 第 5 版规范中,一些实现已经包含这个方法,所以最好的方法是检测本机实现并在它不可用时才声明它:

if (typeof String.prototype.trim != 'function') { // detect native implementation
  String.prototype.trim = function () {
    return this.replace(/^\s+/, '').replace(/\s+$/, '');
  };
}

Then you can simply:然后你可以简单地:

title = title.trim();

I know this is an old post, but just thought I'd share our solution.我知道这是一个旧帖子,但只是想我会分享我们的解决方案。 In the quest for shortest code (doesn't everyone just love terse regex), one could instead use:为了寻求最短的代码(不是每个人都喜欢简洁的正则表达式),可以改为使用:

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

BTW: I ran this same test through the link shared above blog.stevenlevithan.com -- Faster JavaScript Trim and this pattern beat all the other HANDS down!顺便说一句:我通过blog.stevenlevithan.com上面共享的链接进行了同样的测试 ——更快的 JavaScript Trim和这种模式击败了所有其他人!

Using IE8, added test as test13.使用IE8,添加测试为test13。 The results were:结果是:

Original length: 226002原长度:226002
trim1: 110ms (length: 225994)修剪 1:110 毫秒(长度:225994)
trim2: 79ms (length: 225994)修剪 2:79 毫秒(长度:225994)
trim3: 172ms (length: 225994)修剪 3:172 毫秒(长度:225994)
trim4: 203ms (length:225994)修剪 4:203 毫秒(长度:225994)
trim5: 172ms (length: 225994)修剪 5:172 毫秒(长度:225994)
trim6: 312ms (length: 225994) trim6:312ms(长度:225994)
trim7: 203ms (length: 225994)修剪7:203ms(长度:225994)
trim8: 47ms (length: 225994) trim8:47ms(长度:225994)
trim9: 453ms (length: 225994)修剪 9:453 毫秒(长度:225994)
trim10: 15ms (length: 225994)修剪 10:15 毫秒(长度:225994)
trim11: 16ms (length: 225994)修剪 11:16 毫秒(长度:225994)
trim12: 31ms (length: 225994)修剪 12:31 毫秒(长度:225994)
trim13: 0ms (length: 226002)修剪 13:0 毫秒(长度:226002)

ECMAScript 5 supports trim and this has been implemented in Firefox. ECMAScript 5 支持trim ,这已在 Firefox 中实现。

trim - MDC 修剪 - MDC

Here, this should do all that you need在这里,这应该可以满足您的所有需求

function doSomething(input) {
    return input
              .replace(/^\s\s*/, '')     // Remove Preceding white space
              .replace(/\s\s*$/, '')     // Remove Trailing white space
              .replace(/([\s]+)/g, '-'); // Replace remaining white space with dashes
}

alert(doSomething("  something with  some       whitespace   "));

Just use string.trim() method.只需使用string.trim()方法。 It's supported by all major browsers.所有主要浏览器都支持它。 Reference here: http://www.w3schools.com/jsref/jsref_trim_string.asp参考这里: http : //www.w3schools.com/jsref/jsref_trim_string.asp

Here is some methods I've been used in the past to trim strings in js:以下是我过去用于在 js 中修剪字符串的一些方法:

String.prototype.ltrim = function( chars ) {
    chars = chars || "\\s*";
    return this.replace( new RegExp("^[" + chars + "]+", "g"), "" );
}

String.prototype.rtrim = function( chars ) {
    chars = chars || "\\s*";
    return this.replace( new RegExp("[" + chars + "]+$", "g"), "" );
}
String.prototype.trim = function( chars ) {
    return this.rtrim(chars).ltrim(chars);
}

Here is my current code, the 2nd line works if I comment the 3rd line, but don't work if I leave it how it is.这是我当前的代码,如果我评论第 3 行,则第 2 行有效,但如果我保持原状,则不起作用。

var page_title = $(this).val().replace(/[^a-zA-Z0-9\s]/g, '');
page_title = page_title.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
page_title = page_title.replace(/([\s]+)/g, '-');

jQuery.trim(" hello, how are you? "); jQuery.trim(" 你好,你好吗?");

:) :)

When the DOM is fully loaded, you can add this to all the text fields.当 DOM 完全加载时,您可以将其添加到所有文本字段。 I have never had a situation where I needed to submit leading or trailing space, so doing it all the time globally has worked for me...我从来没有遇到过需要提交前导或尾随空格的情况,所以在全球范围内一直这样做对我有用......

$(function() { $('input[type=text]').on('blur', function(){
    $(this).val($.trim($(this).val()));
  });
});

This is what is suggested by JavaScript Architect/Guru Douglas Crockford.这是 JavaScript 架构师/Guru Douglas Crockford 建议的。

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

Note: you have to define "method" for Function.prototype.注意:您必须为 Function.prototype 定义“方法”。

Alternatively或者

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

title.trim();    // returns trimmed title

Observation观察

In recent browsers, the trim method is included by default.在最近的浏览器中,默认包含trim方法。 So you don't have to add it explicitly.所以你不必明确添加它。

Major browsers Chrome, Firefox, Safari etc. supports trim method.主流浏览器 Chrome、Firefox、Safari 等都支持修剪方法。 Checked in Chrome 55.0.2883.95 (64-bit), Firefox 51.0.1 (64-bit), Safari 10.0 (12602.1.50.0.10).在 Chrome 55.0.2883.95(64 位)、Firefox 51.0.1(64 位)、Safari 10.0(12602.1.50.0.10)中检查。

var word = " testWord ";   //add here word or space and test

var x = $.trim(word);

if(x.length > 0)
    alert('word');
else
    alert('spaces');

a recursive try for this为此递归尝试

function t(k){ 
    if (k[0]==' ') {
        return t(k.substr(1,k.length));
    } else if (k[k.length-1]==' ') {
        return t(k.substr(0,k.length-1));
    } else {
        return k;
    }
}

call like this:像这样调用:

t("      mehmet       "); //=>"mehmet"

if you want to filter spesific chars you can define a list string basically:如果你想过滤特定的字符,你基本上可以定义一个列表字符串:

function t(k){
    var l="\r\n\t "; //you can add more chars here.
    if (l.indexOf(k[0])>-1) {
        return t(k.substr(1,k.length));
    } else if (l.indexOf(k[k.length-1])>-1) {
        return t(k.substr(0,k.length-1));
    } else {
        return k;
    }
}

You can use trimLeft() and trimRight() also.您也可以使用trimLeft()trimRight()

const str1 = "   string   ";
console.log(str1.trimLeft()); 
// => "string   "

const str2 = "   string   ";
console.log(str2.trimRight());
// => "    string"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM