gpt4 book ai didi

javascript - 如何获取以下 ES6 循环中的前面的文本?

转载 作者:行者123 更新时间:2023-12-03 10:22:33 25 4
gpt4 key购买 nike

我正在使用 ES6 编写 Markdown 解析器:

输入:

# Title

* * *

Paragraph

Another paragraph

示例代码:

// create a find/replace based on a regex and replacement 
// to later be used with the conversion functions
function massReplace(text, replacements) {
let result = text
for (let [regex, replacement] of replacements) {
result = result.replace(regex, replacement)
}
return result
}

// match text with # and replace them for html headings
function convertHeadings(text, orig) {
if (orig.match(/^#{1,6}\s/)) {
return massReplace(text,
[/^### (.*)/gm, '<h3>$1</h3>'],
[/^## (.*)/gm, '<h2>$1</h2>'],
[/^# (.*)/gm, '<h1>$1</h1>'] ]
)
}
}

// match text without # and surround them with p tags
function convertParagraphs(text, orig) {
if (!orig.match(/^#{1,6} (.*)/)) {
return `<p>${text}</p>`
}
}

// take the source, split on new lines, make a copy (to
// have a "clean" version to be used in the if statements),
// and finally apply the conversion functions to them with
// the help of a loop and excluding those that output undefined
function convertToHTML(markdownSource) {
let data = markdownSource.split('\n\n')
, orig = data.slice()
, conversions = [ convertHeadings, convertParagraphs]

for (let i = 0, l = orig.length; i < l; ++i) {
for (let conversion of conversions) {
let result = conversion(data[i], orig[i])
if (result !== undefined) {
data[i] = result
}
}
}

return data.join('\n\n')
}

我现在想要的是包裹pno-indent 的标签包含 * * * 的文本周围在它之前(上例中的 Paragraph )。问题是,我不知道如何根据前面的文本获取文本(在本例中为 * * *)。

给出一个想法,这是所需的输出:

<h1>Title</h1>

<p>* * *</p>

<p class="no-indent">Paragraph</p>

<p>Another paragraph</p>

最佳答案

您问的是有关标记化和解析的问题,特别是可能的前瞻解析:

维基百科页面:
https://en.wikipedia.org/wiki/Lexical_analysis
https://en.wikipedia.org/wiki/Parsing

StackOverflow 标记化:
https://stackoverflow.com/questions/tagged/token
https://stackoverflow.com/questions/tagged/tokenize

StackOverflow解析问题:
https://stackoverflow.com/questions/tagged/parsing

关于javascript - 如何获取以下 ES6 循环中的前面的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29564526/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com