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.
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.
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.
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."
To replace the first occurrence of a character in Java, use the replaceFirst() method.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With