Jam*_*ery 152 javascript regex
我试图找到一种方法来从标题字符串的开头和结尾修剪空格.我正在使用它,但它似乎没有工作:
title = title.replace(/(^[\s]+|[\s]+$)/g, '');
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
pol*_*nts 216
注意:截至2015年,所有主流浏览器(包括IE> = 9)都支持String.prototype.trim().这意味着对于大多数用例来说,简单地做str.trim()就是实现问题所要求的最佳方式.
Steven Levithan trim在性能方面分析了Javascript中的许多不同实现.
他的建议是:
function trim1 (str) {
return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
Run Code Online (Sandbox Code Playgroud)
用于"快速跨浏览器的通用实现",以及
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;
}
Run Code Online (Sandbox Code Playgroud)
"如果你想在所有浏览器中以极快的速度处理长字符串".
Sto*_*one 68
如果使用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()));
});
Run Code Online (Sandbox Code Playgroud)
或者干脆:
$.trim(string);
Run Code Online (Sandbox Code Playgroud)
CMS*_*CMS 48
正如@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+$/, '');
};
}
Run Code Online (Sandbox Code Playgroud)
然后你可以简单地说:
title = title.trim();
Run Code Online (Sandbox Code Playgroud)
use*_*028 34
我知道这是一个老帖子,但我想我会分享我们的解决方案.在寻求最短的代码(不是每个人都喜欢简洁的正则表达式),人们可以使用:
title = title.replace(/(^\s+|\s+$)/g, '');
Run Code Online (Sandbox Code Playgroud)
顺便说一句:我通过blog.stevenlevithan.com上面共享的链接运行了同样的测试- 更快的JavaScript Trim,这个模式击败了所有其他的HANDS!
使用IE8,添加测试作为test13.结果是:
原始长度:226002
trim1:110ms(长度:225994)
trim2:79ms(长度:225994)
trim3:172ms(长度:225994)
trim4:203ms(长度:225994)
trim5:172ms(长度:225994)
trim6:312ms(长度: 225994)
trim7:203ms(长度:225994)
trim8:47ms(长度:225994)
trim9:453ms(长度:225994)
trim10:15ms(长度:225994)
trim11:16ms(长度:225994)
trim12:31ms(长度:225994)
trim13:0ms(长度:226002)
Caf*_*eek 11
在这里,这应该做你需要的一切
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 "));
Run Code Online (Sandbox Code Playgroud)
以下是我过去在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);
}
Run Code Online (Sandbox Code Playgroud)