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

Asked

Viewed 98 times

2

I am doing a Markdown parser as part of a study on regular expressions, and I would like to use the amount of characters obtained in an excerpt of the expression, as a basis for string substitution, for example:

# Titulo
## Titulo

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

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

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

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

My text is somewhat confusing, but this was the best way I could find to explain the situation.

2 answers

2

You could use something like '## Titulo'.match(/^(#*)\s?(\w+)/);. That way you get everything separated and all you have to do is tell .length on the part with #. I don’t see how you can do all that in one line, but something like that:

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 be like this: http://jsfiddle.net/arfte7zf/

1


I found a simple solution, replace can receive 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+">";
        })

Browser other questions tagged

You are not signed in. Login or sign up in order to post.