Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Markdown to convert double asterisks to bold text in javascript

i'm trying to make my own markdown-able textarea like Stackoverflow has done. The goal is to allow people to type **blah blah** in a textarea and have the output in a div be <span style="font-weight:bold;">blah blah</span>.

I'm having trouble with the javascript to find and replace to the **asterisks with the HTML.

here's a jsfiddle which has gotten the party started: http://jsfiddle.net/trpeters1/2LAL4/14/

here's the JS on that just to show you where I'm at:

$(document.body).on('click', 'button', function() {

var val=$('textarea').val();

var bolded=val.replace(/\**[A-z][0-9]**/gi, '<span style="font-weight:bold;">"'+val+'" </span>');

$('div').html(bolded);
});

and the HTML...

<textarea></textarea>
<div></div><button type="button">Markdownify</button>

any thoughts would be greatly appreciated!

thanks, tim

like image 382
tim peterson Avatar asked Apr 16 '12 03:04

tim peterson


2 Answers

Choose the perfect regex that will fit your needs. If you don't want styling to span through new line and also using ([^*<\n]+) makes sure at least one character is in between styles or else ** without a character in-between will result will become invisible.

function format_text(text){
return text.replace(/(?:\*)([^*<\n]+)(?:\*)/g, "<strong>$1</strong>")
     .replace(/(?:_)([^_<\n]+)(?:_)/g, "<i>$1</i>")
      .replace(/(?:~)([^~<\n]+)(?:~)/g, "<s>$1</s>")
      .replace(/(?:```)([^```<\n]+)(?:```)/g, "<tt>$1</tt>")
}

β€’The downside to the above code is that, you can't nest styles i.e *_Bold and italic_*

To allow nested styles use this πŸ‘‡

format_text(text){
return text.replace(/(?:\*)(?:(?!\s))((?:(?!\*|\n).)+)(?:\*)/g,'<b>$1</b>')
   .replace(/(?:_)(?:(?!\s))((?:(?!\n|_).)+)(?:_)/g,'<i>$1</i>')
   .replace(/(?:~)(?:(?!\s))((?:(?!\n|~).)+)(?:~)/g,'<s>$1</s>')
   .replace(/(?:--)(?:(?!\s))((?:(?!\n|--).)+)(?:--)/g,'<u>$1</u>')
   .replace(/(?:```)(?:(?!\s))((?:(?!\n|```).)+)(?:```)/g,'<tt>$1</tt>');

// extra:
// --For underlined text--
// ```Monospace font```
}

πŸ‘† If you want your style to span through new line, then remove \n from the regex. Also if your new line is html break tag, you can replace \n with <br>

Thank me later!

like image 109
The concise Avatar answered Oct 12 '22 12:10

The concise


The other answers fail when a char is immediately before or after the asterisks.

This works like markdown should:

function bold(text){
    var bold = /\*\*(.*?)\*\*/gm;
    var html = text.replace(bold, '<strong>$1</strong>');            
    return html;
}
    
var result = bold('normal**bold**normal **b** n.');
document.getElementById("output").innerHTML = result;
div { color: #aaa; }
strong { color: #000; }
<div id="output"></div>
like image 37
Justin Avatar answered Oct 12 '22 11:10

Justin