猿问

innerHTML如何去除缩进

各位好:

欲在html中用template标签里面写Markdown,再用jsMarkdown进行处理转换成html,局部dom结构如下:

<div class="content">

  <template type="markdown">

    Welcome

    ====

    My name is Hung

  </template>

</div>

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

但是因为template标签有缩进,导致了marked把内容当做段落代码处理:

https://img3.mukewang.com/5c21e6a90001096c02550124.jpg

https://img4.mukewang.com/5c21e6b2000163b201860098.jpg


请问又没法办法清除这些缩进,但是又不影响正常缩进的方式,或者不用template标签的其他方式


慕勒3428872
浏览 707回答 1
1回答

ITMISS

给你一个思路,统计每一行前面的空白符,得到一个最小值,再按这个最小值清除补上代码document.querySelectorAll('template[type="markdown"]').forEach($template => {&nbsp; var lines = $template.innerHTML.split(/\r\n|\n/)&nbsp; var trimLen = lines.reduce((minLen, line) => {&nbsp; &nbsp; var len = (/\S/.exec(line) || {index: 0}).index&nbsp; &nbsp; if (len < minLen) { return len }&nbsp; &nbsp; return minLen&nbsp; }, Infinity)&nbsp; if (trimLen > 0) {&nbsp; &nbsp; lines = lines.map(line => line.slice(trimLen))&nbsp; }&nbsp; console.log(marked(lines.join('\n')))})
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答