javascript - 如何在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`,)
有没有办法在文件中也得到这个标签的缩进?
解决方案
我发现一个容易进行的:
首先,我计算第一个字符之前的空格数:
const startIndent = Math.max(
0,
previousContent.lastIndexOf(
'\n',
startOfOpeningTagIndex
)
);
const nbSpaces = startOfOpeningTagIndex
- Math.min(startOfOpeningTagIndex, startIndent);
然后对于我写下的任何内容,我都会添加适当数量的空格:
newContent.replace('\n', '\n' + ' '.repeat(nbSpaces))
推荐阅读
- java - 如何实现 Exo 播放器扩展(Android Studio - JAVA)?
- sql-server - SQL Server BCP 减少输出文件大小
- javascript - why I have this error bash ng command not found while I already installed the angular-cli
- python - 比较两个 csv 文件并将匹配的条目写入第三个文件 python
- c - 为什么我调用函数时程序会停止?
- javascript - Firebase 函数 file.download 返回未定义
- python - 如何取消pyqt5中的透明?
- c++ - 出现错误:对非常量的引用的初始值必须是左值
- amazon-web-services - 无法使用 Amazon Workmail 发送电子邮件
- javascript - 我需要删除复制内容的格式并粘贴到新工作表中