首页 > 解决方案 > 如何在javascript中获取搜索项目的缩进?

问题描述

假设我有以下 .rst 文件:


.. raw:: html

   <!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
   <!-- prettier-ignore-start -->
   <!-- markdownlint-disable -->
   <table>
    <tr>
     <td align="center"><a href = "https://12rambau.github.io/web-resume/"><img src="https://avatars.githubusercontent.com/u/12596392?v=4" width="100px;" alt=""/><br /><sub><b>Rambaud Pierrick</b></sub></a></td>
    </tr>
   </table>
   
   <!-- markdownlint-restore -->
   <!-- prettier-ignore-end -->

   <!-- ALL-CONTRIBUTORS-LIST:END -->

这将在我的文档中显示一个表格。我想用 JS 机器人自动填充它,但是 reST 的问题是缩进很重要。

为了得到我应该开始写作的地方,我使用:

const tagToLookFor = `<!-- ALL-CONTRIBUTORS-LIST:`
const startOfOpeningTagIndex = previousContent.indexOf(`${tagToLookFor}START`,)

有没有办法在文件中也得到这个标签的缩进?

标签: javascriptrestructuredtext

解决方案


我发现一个容易进行的:

首先,我计算第一个字符之前的空格数:

const startIndent = Math.max(
    0,
    previousContent.lastIndexOf(
        '\n', 
        startOfOpeningTagIndex
    )
);

const nbSpaces = startOfOpeningTagIndex 
    - Math.min(startOfOpeningTagIndex, startIndent);

然后对于我写下的任何内容,我都会添加适当数量的空格:

newContent.replace('\n', '\n' + ' '.repeat(nbSpaces))

推荐阅读