gpt4 book ai didi

javascript - 字符串替换某些匹配组,而不是整个匹配

转载 作者:行者123 更新时间:2023-11-29 22:58:56 24 4
gpt4 key购买 nike

在 js 中,我想用一些文本替换字符串中的换行符,但前提是\n 前面有一个点和可选的空格。示例文本:

First sentence comes
split in two lines.

This would be a new sentence.

And the end

应该变成

"First sentence comes split in two lines.<br>This would be a new sentence.<br>And the end"

使用正则表达式:

text = text.replace(/\.\s(*\n)/g, "<br>");

替换整个匹配项,从而吃掉点,据我所知,RegEx.repace 不提供仅替换匹配组的方法。

实现该目标的最简单方法是什么?

最佳答案

您可以捕获组中的文字点,然后是换行符,后跟 0+ 个空白字符。

在替换使用组 1 后跟一个中断:$1<br>

\s*(\.)?\n\s*

Regex demo

const regex = /\s*(\.)?\n\s*/gm;
const str = `First sentence comes
split in two lines.

This would be a new sentence.

And the end`;
const subst = `$1<br>`;
const result = str.replace(regex, subst);

console.log(result);

如果要删除第一个<br>同样,您也可以选择分两步完成:

const str = `First sentence comes   
split in two lines.

This would be a new sentence.

And the end`;
const result = str.replace(/\s*(\.)\s*/g, "$1<br>").replace(/\s*\n+\s*/g, " ");
console.log(result);

关于javascript - 字符串替换某些匹配组,而不是整个匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56028202/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com