How to remove indent from innerHTML - Stack Overflow
世界只因有你
世界只因有你 2017-06-24 09:43:31
0
2
1008

solved

Hello, everyone:

If you want to use template to write Markdown in the tag, then use js to process Markdown and convert it into html, the local dom structure is as follows:

<p class="content">
  <template type="markdown">
    Welcome
    ====
    My name is Hung
  </template>
</p>
<script type="text/javascript">
  document.addEventListener('DOMContentLoaded' ,function (event){
    var $templates = document.querySelectorAll('template[type="markdown"]')
    $templates.forEach(function ($template){
      console.log(marked($template.innerHTML));
    })
  })
</script>

But because the template tag is indented, marked treats the content as paragraph code:

Is there any way to clear these indents without affecting the normal indentation method, or other methods that do not use the template tag?

世界只因有你
世界只因有你

reply all(2)
黄舟

To give you an idea, count the whitespace characters in front of each line, get a minimum value, and then press this minimum value to clear it

Add the code

document.querySelectorAll('template[type="markdown"]').forEach($template => {
  var lines = $template.innerHTML.split(/\r\n|\n/)

  var trimLen = lines.reduce((minLen, line) => {
    var len = (/\S/.exec(line) || {index: 0}).index
    if (len < minLen) { return len }
    return minLen
  }, Infinity)

  if (trimLen > 0) {
    lines = lines.map(line => line.slice(trimLen))
  }

  console.log(marked(lines.join('\n')))
})
仅有的幸福
document.querySelectorAll('template[type="markdown"]').forEach(($template) => {
  let lines = $template.innerHTML.split('\n')
  let linesNum = lines.length
  if (linesNum > 0){
    !!/^\s*$/.test(lines[0]) && lines.shift()
    !!/^\s*$/.test(lines[linesNum-1]) && lines.pop()
  }
  let markdown = lines.map(line => line.substring(Math.min(...lines.map(line => line.match(/^\s*/)[0].length)))).join('\n')
  $template.parentElement.innerHTML = marked(markdown)
})
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template