• 增强分割字符串

代码实现

1. JavaScript

/** @param selector 返回真值表示改匹配项将会被作为分割符 */
function selectiveSplit(str: string, splitRgx: RegExp, selector: (match: RegExpMatchArray) => any): string[] {
    let rst: string[] = []
    let preSplitEnd: number = -1
    for (const match of str.matchAll(splitRgx)) {
        if (selector(match)) {
            rst.push(str.slice(preSplitEnd + 1, match.index));
            preSplitEnd = match.index as number + match[0].length -1
        }
    }
    rst.push(str.slice(preSplitEnd + 1))
    return rst
}

1.1. 使用例

let rst = selectiveSplit('aa-bb-cc', /-/g, (match) => {
    return match.index == 2 ? 0 : 1
})
console.log(rst)//[ 'aa-bb', 'c' ]