Mehran
Mehran

Reputation: 323

String split based on repetitions

I have a string value ("11112233"). I want to split this string and separate it to 3 different value.

Val 1 = 1111
val 2 = 22    
val 3 = 33

I searched a lot, its possible with characters like (/) or other symbols. Something else, My number is always different, so i cant split it by enter the exact string. I want to do something like this:

var myVal = "11112233";
var lastVal = myVal.split(0 , 3); // split from index 0 till index 3

How i can do it?
Thanks

Upvotes: 7

Views: 328

Answers (5)

Dominik G
Dominik G

Reputation: 614

To complement above answers, here's solution not using regex.

function partition(acc, value){

  var last = acc[acc.length-1];
  if(last && last[0] == value) acc[acc.length-1] += value;
  else acc = acc.concat(value);

  return acc;
}

var toInt = parseInt.bind(null, 10)

var x = ([[]]).concat("112233".split(''))
              .reduce(partition).map(toInt);

// [11, 22, 33]

Upvotes: 2

suvroc
suvroc

Reputation: 3062

There is the substr() function.

You can use it like you've written in your question:

var myVal = "11112233";
var lastVal = myVal.substr(0, 3); // "1111"

Upvotes: 2

user1636522
user1636522

Reputation:

Try this regular expression:

'121112233'.match(/(\d)\1*/g) // ["1", "2", "111", "22", "33"]

\1* means "same as previous match, zero or more times".

Upvotes: 14

Nikhil Maheshwari
Nikhil Maheshwari

Reputation: 2248

You can use object to solve this.

var str = '11112233';

var strObj = {};

for(var i = 0; i < str.length; i++){
     if(strObj[str[i]]) {
         strObj[str[i]]+=str[i];
     } else {
        strObj[str[i]] = str[i];
     }
}

for (var key in strObj) {
  if (strObj.hasOwnProperty(key)) {
    alert(key + " -> " + strObj[key]);
  }
}

JsFiddle : https://jsfiddle.net/nikdtu/7qj3szo2/

Upvotes: 3

Man Programmer
Man Programmer

Reputation: 5356

Try like this

myVal='11112233'
myVal.match(/(\d)\1+/g); //["1111", "22", "33"]

Upvotes: 4

Related Questions