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.repl
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, '-');
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;
}
}
var word = " testWord "; //add here word or space and test
var x = $.trim(word);
if(x.length > 0)
alert('word');
else
alert('spaces');
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);
ECMAScript 5 supports trim
and this has been implemented in Firefox.
trim - MDC
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);
}