Alex Rivera | Logout

Javascript replace matched group

Asked 2012-06-12T22:51:53.867
16

I'm trying to build a text formatter that will add p and br tags to text based on line breaks. I currently have this:

s.replace(/\n\n/g, "\n</p><p>\n");

Which works wonderfully for creating paragraph ends and beginnings. However, trying to find
instances isn't working so well. Attempting to do a matched group replacement isn't working, as it ignores the parenthesis and replaces the entire regex match:

s.replace(/\w(\n)\w/g, "<br />\n");

I've tried removing the g option (still replaced entire match, but only on first match). Is there another way to do this?

Thanks!

Edit
Report

1 Answer

25

You can capture the parts you don't want to replace and include them in the replacement string with $ followed by the group number:

s.replace(/(\w)\n(\w)/g, "$1<br />\n$2");

See this section in the MDN docs for more info on referring to parts of the input string in your replacement string.

answered 2012-06-12T22:55:21.820

Your Answer