Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript replace matched group

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!

like image 724
Asherlc Avatar asked Jun 12 '12 22:06

Asherlc


People also ask

How do I match a group in regex?

Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d", "o", and "g".

What is capturing group in regex JavaScript?

Groups group multiple patterns as a whole, and capturing groups provide extra submatch information when using a regular expression pattern to match against a string. Backreferences refer to a previously captured group in the same regular expression.

How do you replace a section of a string in regex?

To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring. The string 3foobar4 matches the regex /\d. *\d/ , so it is replaced.

Can regex replace characters?

They use a regular expression pattern to define all or part of the text that is to replace matched text in the input string. The replacement pattern can consist of one or more substitutions along with literal characters. Replacement patterns are provided to overloads of the Regex.


2 Answers

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.

like image 114
Paul Avatar answered Sep 28 '22 07:09

Paul


Catch the surrounding characters also:

s.replace(/(\w)(\n\w)/g, "$1<br />$2");
like image 43
Guffa Avatar answered Sep 28 '22 09:09

Guffa