Limiting the times that .split() splits, rather than truncating the resulting array

后端 未结 8 1528
耶瑟儿~
耶瑟儿~ 2020-12-11 01:58

Really, pretty much what the title says.

Say you have this string:

var theString = \"a=b=c=d\";

Now, when you run theString

8条回答
  •  感情败类
    2020-12-11 02:49

    The answer from Asad is excellent as it allows for variable length RegExp separators (e.g. /\s+/g, splitting along any length of whitespace, including newlines). However, there are a couple issues with it.

    1. If the separator does not use the global flag, it will break.
    2. The exec can return null and cause it to break. This can happen if the separator does not appear in the input string.

    The following addresses these two issues:

    export function split(input, separator, limit) {
      if (!separator.global) {
        throw new Error("The split function requires the separator to be global.");
      }
    
      const output = [];
    
      while (limit--) {
        const lastIndex = separator.lastIndex;
        const search = separator.exec(input);
        if (search) {
          output.push(input.slice(lastIndex, search.index));
        }
      }
    
      output.push(input.slice(separator.lastIndex));
    
      return output;
    }
    

提交回复
热议问题