Split string in JavaScript using RegExp ignoring the delimiter inside brackets

后端 未结 2 957
名媛妹妹
名媛妹妹 2020-12-06 20:45

I have various instances of strings that I need to split. Following are some examples and the desired output scenarios. The rules to split are also listed:

Example 1

2条回答
  •  既然无缘
    2020-12-06 21:31

    I can't think of regex right now, but you can do this:

    function doSplit(input) {
        var tmp = input.split('|');
    
        var result = [];
        for (var i = 0, j = 0; i < tmp.length; i++) {
            result[j] = (result[j] ? result[j] + '|' : '') + tmp[i];
            if (result[j].indexOf('[') == -1 || result[j].indexOf(']') != -1) {
                j++;
            }
        }
    
        return result;
    }
    
    var i = 'qualifier1[filename.ext|someattributes]|qualifier2[another_filename.ext|some_other_attributes]';
    var o = doSplit(i);
    

提交回复
热议问题