如何在 javascript 中获取搜索项的缩进?

how to get the indent of a searched item in 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 -->

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

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

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

有没有办法在文件中同时获取此标记的缩进?

我找到了一个容易进行的方法:

首先我数一下第一个字符前的空格数:

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

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

然后无论我写下什么,我都会添加适当数量的空格:

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