Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace First N Occurrences in the String

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 s p a c  e  s.js

I am expecting the following result:

07/12/2017|11:01|AM|21523|filename with s p a c  e  s.js

I know not very elegant option only via calling replace N times on the same string

.replace(/\s+/, "|").replace(/\s+/, "|").replace(/\s+/, "|");

Worth to mention that I'm going to run this on near 1,000,000 lines so performance matters.

like image 594
Systems Rebooter Avatar asked Nov 10 '17 20:11

Systems Rebooter


People also ask

How do you replace first occurrence?

Use the replace() method to replace the first occurrence of a character in a string. The method takes a regular expression and a replacement string as parameters and returns a new string with one or more matches replaced.

How do you replace all occurrences in a string?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag.

How do I change the first occurrence of a string in Python?

A string is immutable in Python, therefore the replace() function returns a copy of the string with modified content. To replace only first occurrence of “is” with “XX”, pass the count value as 1. For example: strValue = "This is the last rain of Season and Jack is here."

How do I change the first occurrence of a string in Java?

To replace the first occurrence of a character in Java, use the replaceFirst() method.


1 Answers

Probably something like this:

var txt = "07/12/2017  11:01 AM             21523 filename with s p a c  e  s.js";

var n = 0, N = 4;
newTxt = txt.replace(/\s+/g, match => n++ < N ? "|" : match);

newTxt; // "07/12/2017|11:01|AM|21523|filename with s p a c  e  s.js"
like image 77
Derek 朕會功夫 Avatar answered Oct 11 '22 05:10

Derek 朕會功夫