遍历 HTML 并将字符串替换为 javascript 和正则表达式

Loop through HTML and replace strings with javascript and Regex

提问人:lukaskupfing 提问时间:9/22/2023 更新时间:9/22/2023 访问量:59

问:

我在 Anki 中有这个 HTML:

<p>[!Quote] Title of callout 1<br>Content of callout 1</p>
<p>[!Quote] Title of callout 2<br>Content of callout 2</p>
<p>[!Quote] Title of callout 3<br>Content of callout 3</p>

并希望它看起来像这样:

<p><b>Title of callout 1</b><br>Content of callout 1</p>
<p><b>Title of callout 2</b><br>Content of callout 2</p>
<p><b>Title of callout 3</b><br>Content of callout 3</p>

所以我想删除并加粗。我想出了这个javascript代码:[!Quote]Title of callout

var quoteRegex = /<p>\[!Quote].*(?=<br>)/g;
var title = /(?<=\[!Quote]\s).*(?=<br>)/g;
var back = document.getElementById('back'); // Backside of flashcard containing the paragraphs
var titleString = back.innerHTML.match(title);
back.innerHTML = back.innerHTML.replace(quoteRegex, '<b>' + titleString + '</b>');

但是卡在那里,因为匹配所有标题并用逗号分隔它们,因此当我尝试时会导致这样的事情:titleStringback.innerHTML.replace

<p><b>Title of callout 1, Title of callout 2, Title of callout 3</b><br>Content of callout 1</p>

因此,我认为我需要循环浏览段落,以便我可以一个接一个地替换标题,但我不知道如何完成。提前感谢您的帮助!

javascript html anki

评论


答:

1赞 Orifjon 9/22/2023 #1

正则表达式还有另一种方法。匹配并替换它,而不是回溯。[!Quote]

const regex = /(?<quote>\[!Quote]\s)(?<title>.*)(?=<br>)/g;

// Alternative syntax using RegExp constructor
// const regex = new RegExp('(?<quote>\\[!Quote]\\s)(?<title>.*)(?=<br>)', 'g')

const back = document.getElementById('back');
const subst = `<b>${title}</b>`;

// The substituted value will be contained in the result variable
back.innerHTML = = back.innerHTML.replace(regex, subst);

评论

0赞 lukaskupfing 9/23/2023
谢谢!最初没有工作,让它像这样工作:var extraRegex = /(?<quote>\[!Quote]\s)(?<title>.*)(?=<br>)/g;; back = document.getElementById('back');; back.innerHTML = back.innerHTML.replace(extraRegex, '<b>$<title></b>');
1赞 Alexander Nenashev 9/22/2023 #2

使用捕获组引用:

const html = `<p>[!Quote] Title of callout 1<br>Content of callout 1</p>
<p>[!Quote] Title of callout 2<br>Content of callout 2</p>
<p>[!Quote] Title of callout 3<br>Content of callout 3</p>`;

$div.innerHTML = html.replace(/\[\!Quote\]\s*(.*?)<br>/g, '<b>$1</b><br>');
<div id="$div"></div>

评论

0赞 lukaskupfing 9/23/2023
谢谢!我不知道如何捕获组引用。