我如何模仿innerHTML中的降价替换?

时间:2017-01-19 16:48:15

标签: javascript regex

我正在尝试使用javascript正则表达式来模仿markdown。我想写一个函数来转:

# n11
## n21
### n31
### n32
## n22
# n12
## n23
hello
# n31
## n24
# n41

成:

1. n11<br />
1.1. n21<br />
1.1.1. n31<br />
1.1.2. n32<br />
1.2. n22<br />
2. n12<br />
2.1. n23<br />
hello
1. n31<br />
1.1. n24<br />
2. n41<br />

我的实验未能找到解决方案。 我想我想要一些正则表达式,找到以“###”开头的行序列作为单个匹配。 有没有人知道如何让正则表达式合作? 我使用的是:

text=text.replace(/^\s*###\s+([^]+)$/, replace3);
text=text.replace(/^\s*##\s+([^]+)$/, replace2);
text=text.replace(/^\s*#\s+([^]+)$/, replace1);

但没有一项试验有效。

最有用的方法是让编号在正则表达式替换函数中起作用,其中编号在非“#”行之后重置。

我可以将它分成几行并使用函数在行列表上操作。 但这比正则表达式效率低。

我可能错过了一些见解。

1 个答案:

答案 0 :(得分:0)

&#13;
&#13;
var text = "# n11\n## n21\n### n31\n### n32\n## n22\n# n12\n## n23\nhello\n# n31\n## n24\n# n41";


function transformMarkdown(text){
    // Maximum depth (maximum number of Ns in N.N.N.N... that we could have)
    var MAXDEPTH = 10;
    
    // Holds the value of the ith number N in N.N.N....
    var sections = new Array(MAXDEPTH);
    
    // Initialise it all to 0 so the first substitution will become 1.1.1.1.1... (0 + 1)
    sections.fill(0, 0, MAXDEPTH - 1);
    
    // Check for: A) A valid sustitution (\s*#+.*). B) Not valid substitution (\s* [^#\n]+) so we can initialize our sections array when we don't have a substitution
    return text.replace(/(^\s*(#+)(.*)$)|(^\s*[^#\n]+$)/mg, function(match, substitution, sharps, after){
        // if this line is not a valid substitution reinitialize sections with zeros
        if(!substitution){
            // reinitialize sections
            sections.fill(0, 0, MAXDEPTH - 1);
            // return match so nothing is replaced
            return match;
        }
        
        // length - 1 represent the depth of this substitution
        var length = sharps.length;
        // reinitialize all substitutions after this depth to zero so when we go from 1.2. to 1.3. all the sections N after 3. (1.3.N.N.N.N...) will be initialized to 0
        sections.fill(0, length, MAXDEPTH - 1);
        
        // increment the section of this depth (if length is 2 ans sections is 1.2. then it will become 1.3)
        sections[length - 1]++;
        
        // replacement for the ####... string
        var replacement = "";
        for(var i = 0; i < length; i++)
            // each # will be replaced by its equivalent section according to which depth (i) it's on
            replacement += sections[i] + ".";
        
        // ignore the leading spaces, replace 'sharps' with 'replacement' and insert whatever was after 'sharps'
        return replacement + after;
    })
}

console.log("BEFORE:\n", text);
console.log("AFTER:\n", transformMarkdown(text));
&#13;
&#13;
&#13;