Coding Critique is the place to post source code for peer review by other members of DevNetwork. Any kind of code can be posted. Code posted does not have to be limited to PHP. All members are invited to contribute constructive criticism with the goal of improving the code. Posted code should include some background information about it and what areas you specifically would like help with.
Popular code excerpts may be moved to "Code Snippets" by the moderators.
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*$/, '');
}
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]
1. This is client-side. Like, if you want to strip a form input field, before validating it client-side.
2. Didn't know whether to post it directly in the snippets forum... Thought it could use some scrutiny before being an "official" code-snippet.
Users do not have write access to the snippet forum.
Both of the functions perform differing actions. The first doesn't catch all whitespace characters while the second catches more that just whitespace characters.
A Google search for "javascript trim" will turn up several examples of more straight-forward variants.
tores wrote:1. This is client-side. Like, if you want to strip a form input field, before validating it client-side.
2. Didn't know whether to post it directly in the snippets forum... Thought it could use some scrutiny before being an "official" code-snippet.
Yeah sorry, for some bizarre reason my brain omitted the word JavaScript in your initial post