up vote 1 down vote favorite

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

link|flag
Please indent your code blocks with four spaces at the start of each line. – Gumbo Dec 24 '09 at 13:42
Thanks for the heads-up, will make sure I do this in future – Gids Dec 24 '09 at 13:54

2 Answers

up vote 2 down vote accepted

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

link|flag
Great, many thanks for the super-speedy and helpful response. – Gids Dec 24 '09 at 13:56
I thought this wouldn't work in IE 6 but in fact it does. Turns out IE 5 was the last version that didn't support a function as the second parameter in String.replace. – Tim Down Dec 24 '09 at 14:18
up vote 2 down vote

Here's a version without using a regular expression. You can use the split() method of String, though frankly I'd use the neater regular expression version.

var testVar = "My first line\n\nMy second line\n\nMy third line";
var lines = testVar.split("\n\n"), newStringParts = [];
for (var i = 0, len = lines.length; i < len; ++i) {
    newStringParts.push(i + 1);
    newStringParts.push(lines[i]);
}
alert( newStringParts.join("\n") );
link|flag
It's always a good idea to look at the non-regexp alternatives – Andy E Dec 24 '09 at 14:56

Your Answer

get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.