首页 > 解决方案 > 如何使用正则表达式替换 HTML 标签中的换行符?

问题描述

如何使用来替换标签之间RegExp的每个单独的\n字符?<code> </code>

下面的代码太从字面上理解我的问题。它与 in 匹配\n<code></code>\n<code></code>因为它在技术上位于开始标签和结束<code>标签之间。

const string = `<!DOCTYPE html>
<html>
<head></head>
<body>
<code>function foo() {

console.log('Hello');

}</code>
<code>function bar() {

console.log('World!');

}</code>
</pre>
</body>
</html>`;

const regExp = /(?<=<code>.*)\n(?=.*<\/code>)/gs;
const newString = string.replace(regExp, '<br>');

console.log(newString);

标签: javascriptregexhtml-parsingnewline

解决方案


const string = `<!DOCTYPE html>
<html>
<head></head>
<body>
<code>function foo() {

console.log('Hello');

}</code>
<code>function bar() {

console.log('World!');

}</code>
</pre>
</body>
</html>`;

const regExp = /(?<=<code>(?:(?!<\/?code).)*)\n(?=(?:(?!<\/?code).)*<\/code>)/gs;;
const newString = string.replace(regExp, '<br>');

console.log(newString);


推荐阅读