Trying to find a way to trim spaces from the start and end of the string. I was using this, but it dont seem to be working:
title = title.replace(/(^[\s]+|[\s]+$)/g, '');
Any ideas?
Trying to find a way to trim spaces from the start and end of the string. I was using this, but it dont seem to be working:
title = title.replace(/(^[\s]+|[\s]+$)/g, '');
Any ideas?
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);
}
ECMAScript 5 supports trim
and this has been implemented in Firefox.
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 "));
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".
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, '-');
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();