如何使用正则表达式替换 HTML 标签中的换行符?
How to use regex to replace newlines in HTML tags?
如何使用 RegExp
替换 <code>
</code>
标签之间的每个 \n
字符?
下面的代码从字面上理解了我的问题。它与 <code></code>\n<code></code>
中的 \n
匹配,因为它在技术上介于开始和结束 <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);
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);
如何使用 RegExp
替换 <code>
</code>
标签之间的每个 \n
字符?
下面的代码从字面上理解了我的问题。它与 <code></code>\n<code></code>
中的 \n
匹配,因为它在技术上介于开始和结束 <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);
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);