如何通过数组中的索引查找 Javascript 中的子字符串

How to find the substrings in Javascript by indeces in array

我是 Javascript 的新人。我有一些索引的字符串和数组。

var string = "?str!ing."; //input string
var arr = [0, 4, 8]; // indices of the punctuation signs in the string

如何查找子字符串:

["?", "str", "!", "ing", "."]

提前致谢。

快速解决方案是使用预定义的分隔符列表:

splitString = function(string, splitters) {
    var list = [string];
    for(var i=0, len=splitters.length; i<len; i++) {
        traverseList(list, splitters[i], 0);
    }
    return flatten(list);
}

traverseList = function(list, splitter, index) {
    if(list[index]) {
        if((list.constructor !== String) && (list[index].constructor === String))
            (list[index] != list[index].split(splitter)) ? list[index] = list[index].split(splitter) : null;
        (list[index].constructor === Array) ? traverseList(list[index], splitter, 0) : null;
        (list.constructor === Array) ? traverseList(list, splitter, index+1) : null;    
    }
}

flatten = function(arr) {
    return arr.reduce(function(acc, val) {
        return acc.concat(val.constructor === Array ? flatten(val) : val);
    },[]);
}

var stringToSplit = "?str!ing.";
var splitList = ["?", "!", "."];
splitString(stringToSplit, splitList);

上面的示例 returns:["str"、"ing"]

我相信这段代码会根据索引断句。

var length = arr.length;
var responce = [];

for (var x = 0; x<length ; x++){
    if(arr[x] == 0){
        var z = string.slice(arr[x],arr[x]+1);
        responce.push(z)
    }else{
        var z = string.slice(arr[x-1]+1,arr[x]);
        responce.push(z)
        var z = string.slice(arr[x],arr[x]+1);
        responce.push(z)
    }
    if((x == length-1) && (arr[x] < string.length-1)){
        var z = string.slice(arr[x]+1,string.length);
        responce.push(z)
    }
}

console.log(responce);

如果 arr 中已有索引,这将用子字符串填充变量 res

var res = [];
if(arr[0] > 0) res.push(string.substring(0, arr[0])); //only needed if the first index is not the start of the string and the first substring has to be added
for(var i = 0; i< arr.length; i++){
    var index = arr[i]; 
    res.push(string.substring(index,++index)); //add the puncutation sign 
    var next = arr[i+1] || string.length; //get the next index (or end of string)
    if(index<next) res.push(string.substring(index, next)); //add the substring if length > 0
}

fiddle

也许另一种方法是在确定索引的同时构建 res 数组,但如果您已经有了索引数组,上述方法应该有效。