skip to Main Content

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("nn", "</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

2

Answers


  1. 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("nn", "</br></br>");
      let step2 = step1.replaceAll(/*(.*?)*/g, "<i>$1</i>");
      let step3 = step2.replaceAll(/**(.*?)**/g, "<b>$1</b>");
      return step3;
    }
    
    console.log(formatString(content))
    Login or Signup to reply.
  2. You could use the ShowdownJS library to handle Markdown to HTML conversion.

    let content = '*Hello*, my **friend** how are you?';
    const converter = new showdown.Converter();
    let res = converter.makeHtml(content);
    console.log(res);
    <script src="https://unpkg.com/showdown/dist/showdown.min.js"></script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search