首页 > 解决方案 > 如何在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 ##

标签: javascriptregex

解决方案


这是有效的,但可能有一种更清洁的方法:

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


推荐阅读