Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regex : how to "update" a matching line using regex?

I have a variable containing a multiline string. This string is made of markdown formated text. I want to convert it a "Telegram" compliant markdown format. To convert titles (identified by lines starting with some "#") to bold and underlined text I have to use the replace(All) function on the input string.

var t = "### Context Analyse\n\nHere comes the analyse...\n\nAnd it continues here.\n\n### And here is another title\n\n";
t = t.replace(/#*(.*)\n\n/g, "__*\\$1*__\n\n");
console.log(t);

I would like, for lines starting with some "#", to remove the "#"s and to make it start with "__*" and end with "*__".

With my current expression all the lines are matching.

What am I doing wrong ?

like image 628
Tuckbros Avatar asked Dec 03 '25 22:12

Tuckbros


2 Answers

* matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy).

by contrast + matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy).

You were matching 0 # and then any char any amount of times which obviously matches every line. Just use the regex /#+(.*)\n\n/g.

var t = "### Context Analyse\n\nHere comes the analyse...\n\nAnd it continues here.\n\n### And here is another title\n\n";
t = t.replace(/#+(.*)\n\n/g, "__*\\$1*__\n\n");
console.log(t);
like image 109
Frox Avatar answered Dec 05 '25 10:12

Frox


Several points:

  • #* matches zero or more # characters, but you want at least one. Use #+ instead.
  • You want to match # only at the beginning of a line. Precede it with ^ and add the m(ultiline) flag because your text consists of several lines.
  • What purpose does the \\ serve? (I have removed it in my example.)

var t = `### Context Analyse

Here comes the analyse...

And it continues here.

### And here is another title

`;
t = t.replace(/^#+(.*)\n\n/gm, "__*$1*__\n\n");
console.log(t);
like image 38
Heiko Theißen Avatar answered Dec 05 '25 10:12

Heiko Theißen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!