Reputation: 1261
I am looking for a way to split a sting like "StringBuilder SB = new StringBuilder();" into an array with seperate words, symbols and spaces
var string = "StringBuilder SB = new StringBuilder();";
var array = string.split(...);
output should be like:
array = ["StringBuilder", " ", "SB", " ", "=", " ", "new", " ", "StringBuilder", "(", ")", ";"];
Upvotes: 1
Views: 99
Reputation: 14982
Not sure this applies all your needs:
"StringBuilder SB = new StringBuilder();".match(/(\s+|\w+|.)/g);
["StringBuilder", " ", "SB", " ", "=", " ", "new", " ", "StringBuilder", "(", ")", ";"]
Upvotes: 4
Reputation: 781
easy-customizable solution:
function mySplit(str) {
function isChar(ch) {
return ch.match(/[a-z]/i);
}
var i;
var result = [];
var buffer = "";
var current;
var onWord = false;
for (i = 0; i < str.length; ++i) {
current = str[i];
if (isChar(current)) {
buffer += current;
onWord = true;
} else {
if (onWord) {
result.push(buffer);
}
result.push(current);
onWord = false;
}
}
if(onWord) {
result.push(buffer);
}
return result;
}
Upvotes: 1