如何在下面的ES6循环中获得前面的文本

How can I get the preceding text in the following ES6 loop?

本文关键字:前面 文本 循环 在下面 ES6      更新时间:2023-09-26

我正在用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')
}

我现在想要的是用类no-indentp标记包装在前面有* * *的文本周围(上例中为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