1

Is there a way to seperate a string into an array based on value? For example if I have a string "1119994444455" how would I turn that into [111, 999,44444,55]? I've attempted doing this but my method doesn't seem to be working.

my code:

var nums = [];

for(i in input){
    i = parseInt(i);

    if(i - beforeI != 0 && beforeI >= 0){
        insertionIndex++;
    }

    nums[insertionIndex] += i.toString();
    console.log(nums[insertionIndex]);

    var beforeI = i
}

1 Answer 1

2

You can simply use a Regular Expression, like this

console.log("1119994444455".match(/(\d)\1*/g));
// [ '111', '999', '44444', '55' ]

Here, (\d) captures a number and \1* matches zero or more occurrences of the same captured number. The g at the end makes sure we don't stop after finding the first such match.

Sign up to request clarification or add additional context in comments.

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.