替换字符串javascript中所有出现的字符串

替换字符串javascript中所有出现的字符串,javascript,regex,Javascript,Regex,我想找到所有\n和:的精确匹配项,并用特定字符串替换中间的字符串 例如,给定此输入: Testing \n string of character \n June,23 2020: the task was completed. \n April,4 2020: All looks \n good 预期结果如下: Testing \n string of character <br><b> June,23 2020</b><br> the t

我想找到所有
\n
的精确匹配项,并用特定字符串替换中间的字符串

例如,给定此输入:

 Testing \n string of character \n June,23 2020: the task was completed. \n April,4 2020: All looks \n good
预期结果如下:

 Testing \n string of character <br><b> June,23 2020</b><br> the task was completed. <br><b> April,4 2020</b></br> All looks \n good
测试\n字符串
2020年6月23日
任务已完成
2020年4月4日
一切看起来都很好\n
const text=`正在测试\n字符串\n 2020年6月23日:任务已完成\2020年4月4日:一切看起来都很好`;
常量newlineColonRegex=/(\n |:)/g
常量replaceWith='
' const newString=text.replace(newlineColonRegex,replaceWith)
log(newString)
您可以使用否定字符类排除两者的匹配

\n([^\n:]+):
取代

<br><br>$1<br><br>


1美元

const regex=/\n([^\n::+:)/g;
const text=`Testing\n string of character\n 2020年6月23日:任务已完成\2020年4月4日:一切看起来都很好`;
常量newlineColonRegex=/\n([^\n:]+):/g;
常量replaceWith='

$1

' const newString=text.replace(newlineColonRegex,replaceWith)
console.log(newString)
我将您的问题编辑为使用代码块而不是块引号。在这个过程中,我还删除了

标记中的额外空格,我认为(基于您的代码片段)这些空格是SO的blockquote代码意外插入的,但我想在这里记下,以防它们是故意插入的。