javascript - 如何在javascript中基于#或##创建目录?
问题描述
我有这样的文字:
var text = `# Algorithms
This chapter covers the most basic algorithms.
## Sorting
Quicksort is fast and widely used in practice
Merge sort is a deterministic algorithm
## Searching
DFS and BFS are widely used graph searching algorithms
Some variants of DFS are also used in game theory applications
# Data Structures
This chapter is all about data structures
It's a draft for now and will contain more sections in the future
# Binary Search Trees`;
我能够得到 # 字符串:
var headers = text.match(/(#[^\n]+)/g);
console.log('headers: ',headers);
["# Algorithms", "## Sorting", "## Searching", "# Data Structures", "# Binary Search Trees"]
现在的要求是我需要根据以下内容创建#
目录##
如果它是单一#
的,然后是双重的,##
那么它是这样的:
1. Algorithms
1.1. Sorting
1.2. Searching
2. Data Structures
3. Binary Search Trees
如何检查它是否是 single #
,然后是 double ##
?
解决方案
这是有效的,但可能有一种更清洁的方法:
let inp = ["# Algorithms", "## Sorting", "## Searching", "# Data Structures", "# Binary Search Trees"]
let curInd = [0, 0];
let out = inp.reduce( (acc, el) => {
let n_of_hashtag = (el.match(/#/g) || []).length;
let inp_without_hashtag = el.replace(/#*/g,'');
if(n_of_hashtag == 1){
acc[el] = `${++curInd[0]}.${inp_without_hashtag}`;
curInd[1] = 1;
} else {
acc[el] = `${curInd[0]}.${curInd[1]++}. ${inp_without_hashtag}`;
}
return acc;
}, {});
console.log(out);
推荐阅读
- c# - 用我的链接替换字符串中的链接
- python - 重命名具有任意顺序和重复列名的多索引列
- sql - 在具有大量活动用户的项目中使用 ASP 身份用户
- reactjs - 卸载时 React Progressive Web App 添加到主屏幕不起作用
- postgresql - PostgreSQL - 为具有多对多关系的多个表创建数据库视图
- angular - 如何使用 Ionic 4 检测平台
- json - 如何从 JSON 对象中检索多个值
- c# - C# 将 ListViewGroup 标题文本更改为粗体
- php - Laravel 迁移不适用于新数据库
- git - 当我第一次从命令行推送现有存储库时