简体   繁体   中英

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!

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.

抓住周围的人物也:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM