Trim
test = test.replace(/(^\s+|\s+$)/g, test);
Or you can use str.trim()
if your browser supports it
test = test.trim();
note: if your need to support a browser that doesn't offer str.trim
, you can always use es5-shim
Compact spaces to one
test = test.replace(/\s+/g, " ");
A one-liner
test = test.trim().replace(/\s+/g, " ");
A couple tests
var cleanString = function(str) {
console.log(str.trim().replace(/\s+/g, " "));
};
var examples = [
" [a] b [c] ",
" [a] [b] [c] [d]",
"[a] b [c] ",
" [a] b [c] "
];
examples.map(cleanString);
Output
[a] b [c]
[a] [b] [c] [d]
[a] b [c]
[a] b [c]