最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - String split based on repetitions - Stack Overflow

programmeradmin9浏览0评论

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

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

Share Improve this question edited Apr 29, 2017 at 5:02 user1636522 asked Sep 2, 2015 at 9:11 MehranMehran 3231 silver badge11 bronze badges 1
  • simply you can do like this '11112233'.split(/(1+|2+|3+)/). but need regex improvements – Raghavendra Commented Sep 2, 2015 at 9:19
Add a comment  | 

5 Answers 5

Reset to default 14

Try this regular expression:

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

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

Try like this

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

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/

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"

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]
发布评论

评论列表(0)

  1. 暂无评论