Replace Or Remove Nth Occurrence Of \n
This is my string: var ok = '\n\n33333333333\n\n\n'; How to replace the 4th occurence of '\n' with ''? Or, how to remove the 4th occurence of '\n'?
Solution 1:
- find n-1 occurences and other characters.
- capture the submatch.
- find the next occurence.
replace the entire match with the captured submatch, and the replacement character/string
"AA33333333333AAA".replace(/((?:[^A]*A){3}[^A]*)A/,"$1k")
(with A
and k
insteead of \n
and ""
so you can more clearly see the results)
Solution 2:
Here's what, at least to me, is a fine readable solution:
var i = 0;
ok = ok.replace(/\n/g, function () {
return ++i == 4 ? "" : "\n";
});
However, it might not win as far as performance is concerned.
Post a Comment for "Replace Or Remove Nth Occurrence Of \n"