search

Home  >  Q&A  >  body text

How to remove indent from innerHTML - Stack Overflow

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?

世界只因有你世界只因有你2804 days ago1070

reply all(2)I'll reply

  • 黄舟

    黄舟2017-06-24 09:45:31

    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')))
    })
    

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-06-24 09:45:31

    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)
    })
    

    reply
    0
  • Cancelreply