1

How can I replace some repeated characters using regex?

This is what I have so far:

let message = "*test* _test_ ~test~"
    
    let replacedMessage = message
        .replace(/~(~*[^~\n]+~*)~/g, '<del>$1</del>')
        .replace(/_(_*[^_\n]+_*)_/g, '<em>$1</em>')
        .replace(/\*(\**[^*\n]+\**)\*/g, '<strong>$1</strong>')
        .replace(/\n/g, '<br>')

return replacedMessage 

These are the desired results:

*test* => <strong> //Bold
_test_ => <em> //Italic
~test~ => <del> //Strikethrough
```test``` => <pre> //Monospaced

How can I do the ``` replacement to <pre>? I was unable to make this replacement with the regex.

Caio Kawasaki
  • 2,894
  • 6
  • 33
  • 69

2 Answers2

1

Based on the other regex patterns you're listing, it looks like you want to allow an unlimited number of the delimiter characters. For example, bold can be *******bold this*******. If you want this same behavior with ```, you can use:

.replace(/`{3}(`*[^`\n]+`*)`{3}/g, "<pre>$1</pre>")

Backtick within regex does not conflict with template literals, so this will work fine.

Demo

jdaz
  • 5,964
  • 2
  • 22
  • 34
  • 1
    Awesome!! I should definitely study a little more regex =) – Caio Kawasaki Jul 15 '20 at 03:37
  • Any reason why you wrapped the capture group with `\`*`? – Bren Jul 15 '20 at 04:14
  • @Bren Only to match the same format as the other regexes in the question. I figured there was some reason the others had been written that way. As I mention in my answer, it allows for matching strings with unlimited numbers of backticks enclosing text that cannot contain backticks. – jdaz Jul 15 '20 at 04:36
0

const message ="```test```" 
const regex = /`{3}([^`{3}]*)`{3}/g;
const result = message.replace(regex, "<pre>$1</pre>");
console.log(result);
theSwapnilSaste
  • 201
  • 2
  • 17