admin管理员组文章数量:1129704
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?
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?
Share Improve this question edited Aug 25, 2014 at 15:43 pjmorse 9,2949 gold badges55 silver badges124 bronze badges asked Jun 8, 2010 at 19:38 James JefferyJames Jeffery 3,4854 gold badges20 silver badges13 bronze badges 4 |15 Answers
Reset to default 223Note: 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 analyzed many different implementation of trim
in Javascript in terms of performance.
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
- blog.stevenlevithan.com -- Faster JavaScript Trim
If using jQuery is an option:
/**
* 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:
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!
Using IE8, added test as test13. The results were:
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)
ECMAScript 5 supports trim
and this has been implemented in Firefox.
trim - 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 "));
Here is some methods I've been used in the past to trim strings in 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.
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, '-');
Just use string.trim()
method. It's supported by all major browsers.
Reference here: http://www.w3schools.com/jsref/jsref_trim_string.asp
jQuery.trim(" hello, how are you? ");
:)
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...
$(function() { $('input[type=text]').on('blur', function(){
$(this).val($.trim($(this).val()));
});
});
This is what is suggested by JavaScript Architect/Guru Douglas Crockford.
String.method('trim', function ( ) {
return this.replace(/^\s+|\s+$/g, '');
});
Note: you have to define "method" for 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. So you don't have to add it explicitly.
Major browsers Chrome, Firefox, Safari etc. supports trim method. Checked in Chrome 55.0.2883.95 (64-bit), Firefox 51.0.1 (64-bit), 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.
const str1 = " string ";
console.log(str1.trimLeft());
// => "string "
const str2 = " string ";
console.log(str2.trimRight());
// => " string"
本文标签: javascriptTrim spaces from start and end of stringStack Overflow
版权声明:本文标题:javascript - Trim spaces from start and end of string - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736738185a1950365.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
.trim
built in now, so this is answer for modern browsers: stackoverflow.com/a/3000900/29182 – Ziggy Commented Jan 24, 2014 at 11:34function 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; }
– Badri Gs Commented Aug 4, 2017 at 5:11