1

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", "(", ")", ";"];
Drew
  • 1,171
  • 4
  • 21
  • 36

2 Answers2

4

Not sure this applies all your needs:

"StringBuilder SB = new StringBuilder();".match(/(\s+|\w+|.)/g);
["StringBuilder", " ", "SB", " ", "=", " ", "new", " ", "StringBuilder", "(", ")", ";"]
vp_arth
  • 14,461
  • 4
  • 37
  • 66
  • So this works simply by copy pasting your snippet, but I am curious how "/(\s|\w+|.)/g" this does what it does? – Drew Jun 27 '16 at 22:06
  • 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(`.`). – vp_arth Jun 27 '16 at 22:09
1

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;
}
Tarwirdur Turon
  • 751
  • 5
  • 17