Replace First N Occurrences in the String

前端 未结 6 1688
终归单人心
终归单人心 2021-01-14 06:45

How can I replace first N occurrences of many whitespaces and tabs in the following string:

07/12/2017  11:01 AM             21523 filename with         


        
6条回答
  •  终归单人心
    2021-01-14 06:51

    What about recursive version of you own solution?

    function repalceLeadSpaces(str, substitution, n) {
        n = n || 0;
        if (!str || n <= 0) {
            return str;
        }
        str = str.replace(/\s+/, substitution);
        return n === 1 ? str : repalceLeadSpaces(str, substitution, n - 1)
    }
    

提交回复
热议问题