Search code examples
javascriptregexreplaceecmascript-5

Use the number of characters obtained in a sentence of the regular expression in the string replacement


I'm doing a Markdown parser as part of a study on regular expressions, I would like to use the number of characters obtained on a stretch of expression, as string replacement base, for example :

# Title
## Title

the first title will be added an H1 because I only have a #, the second will be added an H2 because I have two # .

And I would use the amount of stretch of the characters is the # Regular expression to replace a string, for example :

markdown.replace ( /(\#+) *( +)/ig, "<h?>$2</hr?>");

Where the ? would be the amount found by the expression # .

My entry is somewhat confusing, but this was the best way I found to explain the situation .


Solution

  • I found a simple solution, replace can recieve an function, so I can do anything I need, check my solution:

            markdown = markdown.replace(/(\#+) *(.+)/ig, function(exp, n1, n2){
                size = n1.length;
                return "<h"+size+">"+n2+"</h"+size+">";
            })