Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Javascript RegExp to replace each match with an iterating number

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

like image 725
Gids Avatar asked Dec 24 '09 13:12

Gids


People also ask

What is $1 in regex replace?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.

Can I use regex in replace?

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.

How do you replace all occurrences of a character in a string in JavaScript?

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')


1 Answers

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

like image 143
vava Avatar answered Nov 16 '22 03:11

vava