What is wrong with this simple JavaScript code?
I have the following string:
(1-$500.00)(2-$20.00)
I want to turn it into an开发者_运维百科 array with values looking like this:
output[0] = 1-$500.00
output[1] = 2-$20.00
So I tried this:
var output = '(1-$500.00)(2-$20.00)';
var pattern = "/\\)\\(|\\(|\\)?/";
output = output.split(pattern);
alert(output);
But it just alerts the original string, doesn't get the job done. Is there something wrong with my regex or the way I'm using the split function?
You don't need to quote regexes.
var pattern = /\)\(|\(|\)/;
To ensure the content follows the expected format (verification) and avoid the leading and ending empty entries, I'd use RegExp.exec
instead of String.split
.
function my_split(input) {
var pattern = /\((\d+-\$\d+\.\d+)\)/g;
var output = [];
while((m = pattern.exec(input)))
output.push(m[1]);
return output;
}
精彩评论