A
Alex Vassiliev
Hi all.
Just wanted to share two handy RegEx expressions to strips leading and
trailing white-space from a string, and to replace all repeated spaces,
newlines and tabs with a single space.
* JavaScript example:
String.prototype.trim = function() {
// Strip leading and trailing white-space
return this.replace(/^\s*|\s*$/g, "");
}
String.prototype.normalize_space = function() {
// Replace repeated spaces, newlines and tabs with a single space
return this.replace(/^\s*|\s(?=\s)|\s*$/g, "");
}
" one \t two three \n ".trim(); // --> "one \t two three"
" one \t two three \n ".normalize_space(); // --> "one two three"
Enjoy,
Alex Vassiliev (New Zealand)
Just wanted to share two handy RegEx expressions to strips leading and
trailing white-space from a string, and to replace all repeated spaces,
newlines and tabs with a single space.
* JavaScript example:
String.prototype.trim = function() {
// Strip leading and trailing white-space
return this.replace(/^\s*|\s*$/g, "");
}
String.prototype.normalize_space = function() {
// Replace repeated spaces, newlines and tabs with a single space
return this.replace(/^\s*|\s(?=\s)|\s*$/g, "");
}
" one \t two three \n ".trim(); // --> "one \t two three"
" one \t two three \n ".normalize_space(); // --> "one two three"
Enjoy,
Alex Vassiliev (New Zealand)