javascript - 如何使用正则表达式替换 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);
解决方案
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);
推荐阅读
- c# - 邮件合并不保存c#
- sql-server-2012 - 更新外键表列
- azure-resource-manager - ARM 模板 - 映射不同资源组的应用程序洞察力/应用程序服务计划
- dart - 使用 dart2js 构建非最小化项目
- javascript - FullpageJS如何通过动画将目录转到特定部分但不显示中间部分
- dart - 表单被键盘向上推以及如何删除下拉箭头
- r - 拆分具有 2 个相似词的句子
- php - 我想从数据库中选择数据我的代码有什么错误,
- php - 如何通过在 laravel 5.6 中级联来显示下拉列表中的项目?
- c# - 数据库上下文查询 ToDictionary 其中值是实体列表