views:

378

answers:

3

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

+2  A: 

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

vava
Great, many thanks for the super-speedy and helpful response.
Gids
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
+2  A: 

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") );
Tim Down
It's always a good idea to look at the non-regexp alternatives
Andy E
A: 

To replace image paths with just names in html I did sth like this

html='hello <img src="../../../../yahoo/images/icons/common/image_one.png">a<img \
src="add.png"> xyz <table><tbody><tr><td>He<img src="document_add.png">loo<img\
src="document_add.png"></td></tr></tbody></table><img src="CD_delete.png"><img src="check.png">'


html.replace(/src="(.*?)"/ig, function($1){return 'src="'+$1.match(/([^\/\\]+)\.(\w+)/)[0]+'"'  });

output will be

   "hello <img src="image_one.png">a<img src="src="add.png"> xyz <table><tbody><tr><td>He<img src="src="document_add.png">loo<img src="src="document_add.png"></td></tr></tbody></table><img src="src="CD_delete.png"><img src="src="check.png">"
sakhunzai