By using Javascript, I want to convert text
" [a] b [c]"
to
"[a] b [c]"
My code as below:
var test = " [a] b [c]";
test.replace(/\s+\[/g, "[");
alert(test);
However, the result is
"[a] b [c]"
I wonder why? Any idea?
Thanks!
By using Javascript, I want to convert text
" [a] b [c]"
to
"[a] b [c]"
My code as below:
var test = " [a] b [c]";
test.replace(/\s+\[/g, "[");
alert(test);
However, the result is
"[a] b [c]"
I wonder why? Any idea?
Thanks!
Strings are immutable. So replace doesn't change test but returns a changed string. Hence, you need to assign the result:
test = test.replace(/\s+\[/g, "[");
Note that this will result in [a] b[c]. To get your actual result, you might want to use:
test = test.replace(/(^|\s)\s*\[/g, "$1[");
This makes sure to write back the first of the space characters if it was not at the beginning of the string.
Alternatively, use trim first and write back one space manually:
test = test.trim().replace(/\s+\[/g, " [");
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]