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 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 ?
Share Improve this question edited Mar 22 at 16:34 chrwahl 13.3k2 gold badges23 silver badges35 bronze badges asked Mar 22 at 16:25 TuckbrosTuckbros 4754 silver badges17 bronze badges 1 |2 Answers
Reset to default 6* 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);
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 them
(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);
^
, but also consider anchoring it to the end of string$
instead of matching newlines (and replacing them. Unless you only ever want to match headers when followed by newlines). Also since the header should contain text, I would suggest also using a+
for matching it. Hence I proposet.replace(/^#+(.+)$/gm, "__*$1*__")
. – DuesserBaest Commented Mar 24 at 7:53