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", "(", ")", ";"];
6

2 Answers 2

4

Not sure this applies all your needs:

"StringBuilder SB = new StringBuilder();".match(/(\s+|\w+|.)/g);
["StringBuilder", " ", "SB", " ", "=", " ", "new", " ", "StringBuilder", "(", ")", ";"]
Sign up to request clarification or add additional context in comments.

2 Comments

So this works simply by copy pasting your snippet, but I am curious how "/(\s|\w+|.)/g" this does what it does?
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(.).
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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.