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

2

I'm doing a Markdown parser as part of a regular expression study, and I'd like to use the amount of characters in a stretch of the expression as a basis for string substitution, for example:

# Titulo
## Titulo

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

And I would like to use the amount of characters in the snippet that finds regular expression # to replace a string, for example:

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

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

My text is a bit confusing, but this was the best way I found to explain the situation.

    
asked by anonymous 20.08.2015 / 19:38

2 answers

1

I found a simple solution, replace might get a function, so I can do whatever I want, see my solution:

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

You could use something like '## Titulo'.match(/^(#*)\s?(\w+)/); . That way you get everything separated and you only have to count the .length of the part with # . I do not see how you can do this all in one line, but something like this would already be enough:

var parts = markdown.match(/(#*)\s?(\w+)/);
if (!parts) return '';
var heading = parts[1].length + 1;
var text = parts[2];
return ['<h', heading, '>', text, '</', heading, '>'].join('');

An example would look like this: link

    
20.08.2015 / 20:14