Javascript 从字符串的开头和结尾修剪空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3000649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Trim spaces from start and end of string
提问by James Jeffery
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?
有任何想法吗?
回答by polygenelubricants
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.
注意:截至 2015 年,所有主流浏览器(包括 IE>=9)都支持 String.prototype.trim()。这意味着对于大多数用例,简单地做str.trim()是实现问题的最佳方式。
Steven Levithan analyzed many different implementation of trimin Javascript in terms of performance.
Steven Levithantrim在性能方面分析了Javascript 中的许多不同实现。
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
参考
回答by Stone
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);
回答by CMS
As @ChaosPandionmentioned, the String.prototype.trimmethod has been introduced into the ECMAScript 5th EditionSpecification, some implementationsalready include this method, so the best way is to detect the native implementation and declare it onlyif it's not available:
正如@ChaosPandion提到的,该String.prototype.trim方法已经被引入到ECMAScript 5th EditionSpecification 中,一些实现已经包含了这个方法,所以最好的方法是检测本机实现并只有在它不可用时才声明它:
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();
回答by user590028
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 loveterse 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 Trimand this pattern beat all the other HANDS down!
顺便说一句:我通过blog.stevenlevithan.com上面共享的链接进行了同样的测试——更快的 JavaScript Trim和这种模式击败了所有其他人!
Using IE8, added test as test13. The results were:
使用IE8,添加测试为test13。结果是:
Original length: 226002
trim1: 110ms (length: 225994)
trim2: 79ms (length: 225994)
trim3: 172ms (length: 225994)
trim4: 203ms (length:225994)
trim5: 172ms (length: 225994)
trim6: 312ms (length: 225994)
trim7: 203ms (length: 225994)
trim8: 47ms (length: 225994)
trim9: 453ms (length: 225994)
trim10: 15ms (length: 225994)
trim11: 16ms (length: 225994)
trim12: 31ms (length: 225994)
trim13: 0ms (length: 226002)
原始长度:226002
trim1:110ms(长度:225994)
trim2:79ms(长度:225994)
trim3:172ms(长度:225994)
trim4:203ms(长度:225994)
trim5:172ms(长度:9312)
trim2:172ms(长度:225994)trim3:203ms(长度:225994)225994)
trim7:203ms(长度:225994)
trim8:47ms(长度:225994)
trim9:453ms(长度:225994)
trim10:15ms(长度:225994)
trim11:16ms(长度9:432192)
trim2
修剪 13:0 毫秒(长度:226002)
回答by ChaosPandion
ECMAScript 5 supports trimand this has been implemented in Firefox.
ECMAScript 5 支持trim并且这已在 Firefox 中实现。
回答by CaffGeek
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 "));
回答by azatoth
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);
}
回答by James Jeffery
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, '-');
回答by Leo
Just use string.trim()method. It's supported by all major browsers.
Reference here: http://www.w3schools.com/jsref/jsref_trim_string.asp
就用string.trim()方法吧。所有主要浏览器都支持它。参考这里:http: //www.w3schools.com/jsref/jsref_trim_string.asp
回答by Mark Swardstrom
When the DOM is fully loaded, you can add this to all the text fields. 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...
当 DOM 完全加载时,您可以将其添加到所有文本字段。我从来没有遇到过需要提交前导或尾随空格的情况,所以在全球范围内一直这样做对我有用......
$(function() { $('input[type=text]').on('blur', function(){
$(this).val($.trim($(this).val()));
});
});

