jQuery字符串操作将数字分组在一起 [英] JQuery string manipulation to group numbers together

查看:125
本文介绍了jQuery字符串操作将数字分组在一起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在处理某些表,并尝试在数字1-16之间进行存储,现在信息是从字符串格式的信息中提取的,例如:

So I'm working with some tables and I'm attempting to store between numbers 1-16 now the information is being pulled from information in a string format such as:

  1. 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16
  2. 1,2,3,4,5,6,11,12
  3. 1,2,6,7,8,9,10,12
  1. 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16
  2. 1,2,3,4,5,6,11,12
  3. 1,2,6,7,8,9,10,12

所以我想对数字进行分组,因此,如果说按顺序有3个以上的数字,例如:1,2,3,4,5,它将变成1-3,5

So i would like to group the numbers so if let's say there is more than 3 numbers in order e.g.: 1,2,3,4,5 this would become 1-3,5

因此上述内容将变为:

  1. 1-16
  2. 1-6,11,12
  3. 1, 2,6-10,12
  1. 1-16
  2. 1-6,11,12
  3. 1, 2,6-10,12

我可以采用jQuery中的哪种方法来完成此任务?

What sort of methods in jQuery can i take to accomplish this?

推荐答案

此代码解决了您的问题.我不知道是否涵盖所有情况,但我认为可以.随时从这里适应.

This code solves your problem. I don't know if it covers all case, but I think it does. Feel free to adapt from here.

//var a = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16";
var a = "1,2,3,4,5,6,11,12";
//var a= "1,2,6,7,8,9,10,12";
var arr = a.split(',');
console.log('result', parseString(arr, arr[0], 0, arr[0]));

function parseString(arr, start, idx, res_string) {
    console.log(arr, start,idx, res_string);
    var starter = parseInt(start, 10);

    while (starter + 1 === parseInt(arr[idx + 1], 10)) {
        <!-- console.log(starter +1,parseInt(arr[idx + 1], 10)); -->
        idx += 1;
        starter += 1;
    }

    if (idx + 1 < arr.length && idx !== starter) {
        res_string += '-' + arr[idx] + ',' + arr[idx + 1];
        return parseString(arr, arr[idx + 1], idx + 1, res_string);
    }
    else if (idx === starter) {
        return parseString(arr, arr[idx + 1], idx + 1, res_string);
    }
    else if ( start === arr[arr.length -1]){
        return res_string;
    }
    else{
        res_string += '-' + arr[idx];
        return res_string;

    }
}

这篇关于jQuery字符串操作将数字分组在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆