Javascript 替换匹配组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11005991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:47:14  来源:igfitidea点击:

Javascript replace matched group

javascriptregex

提问by Asherlc

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:

我正在尝试构建一个文本格式化程序,它将根据换行符将 p 和 br 标签添加到文本中。我目前有这个:

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?

我试过删除 g 选项(仍然替换整个匹配,但只在第一次匹配时)。有没有其他方法可以做到这一点?

Thanks!

谢谢!

回答by Paul

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, "<br />\n");

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

有关在替换字符串中引用部分输入字符串的更多信息,请参阅MDN 文档中的这一部分

回答by Guffa

Catch the surrounding characters also:

还要捕捉周围的字符:

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