Javascript strip functions
Posted: Wed Jul 04, 2007 5:53 am
feyd | Please use
-tores
feyd | Please use[/syntax]
Code: Select all
,Code: Select all
and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
These functions strip away any whitespace from the beginning and end of the input string... The first tries to be fast, the second uses regex. Haven't really tested the speed of the two, though.
[syntax="javascript"]
function strip(str) {
if (typeof str != 'string') {
return;
}
var s = 0, e = str.length-1;
var ss = 0, es = 0;
var c = '';
// Look for whitespace from start and end of string
for (var i = 0, j = e, m = str.length/2; i < m; i++, j--) {
c = str[i];
if (ss == 0 && (c == ' ' || c == '\t' || c == '\n')) {
s++;
} else {
ss = 1;
}
c = str[j];
if (es == 0 && (c == ' ' || c == '\t' || c == '\n')) {
e--;
} else {
es = 1;
}
}
// Include centermost char if it's not a whitespace
if (str.length % 2) {
c = str[m+1];
if (c == ' ' || c == '\t' || c == '\n') {
s++;
}
}
c = str.substring(s, e+1);
// If the input string contains only whitespace we still have a single whitespace
if (c == ' ' || c == '\t' || c == '\n') {
c = '';
}
return c;
}
function strip2(str) {
if (typeof str != 'string') {
return;
}
return str.replace(/^\W*/, '').replace(/\W*$/, '');
}
feyd | Please use[/syntax]
Code: Select all
,Code: Select all
and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]