Replace First N Occurrences in the String

前端 未结 6 1750
终归单人心
终归单人心 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:58

    You could take a counter and decrement it.

    var string = '07/12/2017  11:01 AM             21523 filename with s p a c  e  s.js',
        n = 4,
        result = string.replace(/\s+/g, s => n ? (n--, '|') : s);
        
    console.log(result);

    You could replace the ternary expression with one with logical AND and OR.

    var string = '07/12/2017  11:01 AM             21523 filename with s p a c  e  s.js',
        n = 4,
        result = string.replace(/\s+/g, s => n && n-- && '|' || s);
        
    console.log(result);

提交回复
热议问题