Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace text to make markdown or formatting

I want to replace *hello* to hello how will i be able to do that? and the same but with other prefixes

let content = '*Hello*, my **friend** how are you?'

      function formatString(content) {
        let step1 = content.split(" ").join(" ").replaceAll("\n\n", "</br></br>");
        //replace
      }
      formatString(content)//should return '<i>Hello</i>, my <b>friend</b> how are you?'

I tried using regex but I was only able to replace *string* to string only instead of string

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

the replaceAll method with the regex /*(.?)*/g to replace all occurrences of string with string, and /**(.?)**/g to replace all occurrences of string with string. The g flag makes sure that all occurrences are replaced, not just the first one.

let content = '*Hello*, my **friend** how are you?'

function formatString(content) {
  let step1 = content.split(" ").join(" ").replaceAll("\n\n", "</br></br>");
  let step2 = step1.replaceAll(/\*(.*?)\*/g, "<i>$1</i>");
  let step3 = step2.replaceAll(/\*\*(.*?)\*\*/g, "<b>$1</b>");
  return step3;
}

console.log(formatString(content))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading