Replace First N Occurrences in the String

前端 未结 6 1728
终归单人心
终归单人心 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 07:09

    Some answers here are really good already, but since you say you want speed, I'd go with a single while, like this:

    var logLine = '07/12/2017  11:01 AM             21523 filename with s p a c  e  s.js';
    var N = 4;
    while(--N + 1){
      logLine = logLine.replace(/\s+/, '|');
    }
    console.log(logLine);

    Here's on JSFiddle: https://jsfiddle.net/2bxpygjr/

提交回复
热议问题