简体   繁体   中英

Regular Expression for split string in JavaScript

I have the string in like below format:

var string = "1SS+2d,12SS+7d,13SS+12d";

My requirement is split the given string into array with 3 objects like in the following format:

var collection = [{ id : 1,
                    connectiontype : "SS",
                    linelength : 7,
                    linetyype: d
                },
                {
                    id: 12,
                    connectiontype: "SS",
                    linelength: 2,
                    linetyype: d
                },
                {
                    id: 12,
                    connectiontype: "SS",
                    linelength: 2,
                    linetyype: d
                },
                {
                    id: 13,
                    connectiontype: "SS",
                    linelength: 12,
                    linetyype: d
                }            

]

I have tried with split method in string object. But it take more looping logic. How to obtain this using RegExp?

you can use next regular expression to build your object

var regexp = /(\d+)(\w+)\+(\d+)(\w+)/;
var arr = string.split(',');
var collection = [];
var result;
for ( var key in arr ){
    result = regexp.exec(arr[key]);
    collection.push({
        id : result[1],
        connectiontype : result[2],
        linelength : result[3],
        linetyype: result[4]
    });
}

I would recommend using split to split each item using comma, then you can use regex to parse each item to create the object:

var string = "1SS+2d,12SS+7d,13SS+12d";
var regex = /(\d+)(\w+)\+(\d+)(\w+)/;
var match = regex.exec(string);

var collection = [];

var items = string.split(',');
for (var i = 0; i < items.length; i++) {
    var item = items[i];
    var match = regex.exec(item);

    collection.push({
        id: match[1],
        connectiontype: match[2],
        linelength: match[3],
        linetyype: match[4]
    });
}

Here is a working example

Split the string then loop over it. I've assumed that SS and d are going to be the same in each object but YMMV.

var r = /^(\d+)SS\+(\d+)d$/;
var collection = [];
str.split(',').forEach(function (el) {
  var m = r.exec(el);
  var obj = {
    id: m[1],
    connectiontype: 'SS',
    linelength: m[2],
    linetyype: 'd'
  };
  collection.push(obj);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM