I want to replace empty lines in my string with an iterating number
e.g. replace
String:
"My first line
My second line
My third line"
with
"
1
My first line
2
My second line
3
My third line"
I can match and replace these lines using
var newstring = TestVar.replace (/(^|\n\n)/g, "\nhello\n");
However I'm struggling to add a function that will add an iterating number to each one.
Can you help?
TIA,
Gids
For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.
The Regex. Replace(String, String, MatchEvaluator, RegexOptions) method is useful for replacing a regular expression match if any of the following conditions is true: If the replacement string cannot readily be specified by a regular expression replacement pattern.
To make the method replace() replace all occurrences of the pattern you have to enable the global flag on the regular expression: Append g after at the end of regular expression literal: /search/g. Or when using a regular expression constructor, add 'g' to the second argument: new RegExp('search', 'g')
Yes, you can do that in javascript. You just need to pass a function as a second argument to replace
.
var i = 0;
var newstring = TestVar.replace(/(^|\n\n)/g, function() { return '\n' + (++i) + '\n'; });
function actually get a lot of parameters based on which you can decide what value you want to replace with but we don't need any of them for this task.
However, it is good to know about them, MDC has a great documentation on the topic
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