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", "(", ")", ";"];
asked Jun 27, 2016 at 21:34
Drew
1,3116 gold badges22 silver badges39 bronze badges
-
6Cool. What have you tried?Mike Cluck– Mike Cluck2016年06月27日 21:36:24 +00:00Commented Jun 27, 2016 at 21:36
-
msdn.microsoft.com/en-us/library/…Jake Smith– Jake Smith2016年06月27日 21:38:37 +00:00Commented Jun 27, 2016 at 21:38
-
stackoverflow.com/questions/650022/…Blue Boy– Blue Boy2016年06月27日 21:39:30 +00:00Commented Jun 27, 2016 at 21:39
-
developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…SteamDev– SteamDev2016年06月27日 21:39:45 +00:00Commented Jun 27, 2016 at 21:39
-
Just write your own tokenizer. char by char..vp_arth– vp_arth2016年06月27日 21:44:46 +00:00Commented Jun 27, 2016 at 21:44
2 Answers 2
Not sure this applies all your needs:
"StringBuilder SB = new StringBuilder();".match(/(\s+|\w+|.)/g);
["StringBuilder", " ", "SB", " ", "=", " ", "new", " ", "StringBuilder", "(", ")", ";"]
answered Jun 27, 2016 at 21:49
vp_arth
15k4 gold badges43 silver badges72 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Drew
So this works simply by copy pasting your snippet, but I am curious how "/(\s|\w+|.)/g" this does what it does?
vp_arth
It just matches tokens by alternation. One of them (
| separated) should be matched. and if nothing matched last one . means "every single character". So, we split input by spaces(\s+), words(\w+) and other characters(.).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;
}
answered Jun 27, 2016 at 21:53
Tarwirdur Turon
7911 gold badge5 silver badges18 bronze badges
Comments
lang-js