Skip to content
Advertisement

Using symbols in an input to format text

I’m struggling to find a solution which allows a user to input in a input field, however they can style their text when it displays after the input for was submitted.

For example, a user could enter **message** into the input field, JavaScript can detect that the ** on the start of the word/sentence and make this text bold. Essentially StackOverflow does this shown in the image below:

Stackoverflow example of styling input

However my code works, but barely. For instance, the user can input their text, and format it in the input with symbols types such as:

  • ** = Bold
  • * = Italics
  • __ = Underlined, etc

Below is my attempt:

    if (msg.includes('**')) {
        msg = msg.replace("**", "");
        msg = msg.replace("**", "");
        msg = `<b>${msg}</b>`
    }
    if (msg.includes('__')) {
        msg = msg.replace("__", "");
        msg = msg.replace("__", "");
        msg = `<u>${msg}</u>`
    }

However this code would not work and mean a user could just enter **message instead of using it on point a to point b of the text they want to style.

Also, this code would make the whole text the format anyway, I just would like only the text within the formatted symbols. Could anyone please provide a solution?

TL;DR

Simply a user can input their text into an input field, however they may want to format it, let’s say bold, the user within the input can have their text:

User text: This is a **desired** example

Display on page as: This is a desired example

However, my currently non-functioning code applies the format to the whole text instead of the selected within the symbols:

User text: This is a **bad** example

Display on page as: This is a bad example

Advertisement

Answer

You can use

let msg = "This is a **desired** *```example```*"
msg = msg
  .replace(/*{2}([wW]*?)*{2}/g, '<b>$1</b>')
  .replace(/`{3}([wW]*?)`{3}/g, '<code>$1</code>')
  .replace(/*([wW]*?)*/g, '<u>$1</u>')

document.body.innerHTML = msg
  

Details:

  • .replace(/*{2}([wW]*?)*{2}/g, '<b>$1</b>') – wraps the strings between ** and ** with bold tags
  • .replace(/{3}([wW]*?){3}/g, '<code>$1</code>') – wraps strings between triple backticks with <code> tag
  • .replace(/*([wW]*?)*/g, '<u>$1</u>') – wraps texts between single * with underline tags.
Advertisement