Search code examples
javascriptjquerymarkup

jQuery custom markdown for a blockquote


I want to create my own markdown system for my platform.

So, to allow users to make their text bold, they can wrap text in double asterisks.

Here is how I do this:

<div class="content">
   The following will be bold: **I am bold**
</div>

jQuery:

function markdown(markdownable) {

var bold = /\*\*(\S(.*?\S)?)\*\*/gm;
    markdownable = markdownable.replace( bold, '<span style="font-weight:bold">$1</span>' );

    return markdownable;
}

$('.content').each(function() {

    var markdownable = $(this).html(),
        content = markdown(markdownable);

    $(this).html(content);


});

Here is a working fiddle.

Now, to my question. Whenever users add a > at the beginning of a paragraph, like this:

> Hello world, this can be a very lengthy paragraph.

Then I want to wrap that text into <blockquote>.

How can I do this?


Solution

  • hey i have updated your jsfiddle..

    code:-

    function markdown(markdownable) {
            var bold = /\*\*(\S(.*?\S)?)\*\*/gm;
        markdownable = markdownable.replace(bold, '<span style="font-weight:bold">$1</span>');
    
        if (markdownable.indexOf("&gt;") == 0) {
            markdownable = markdownable.replace("&gt;", "<blockquote>");
            markdownable += "</blockquote>";
        }
        return markdownable;
    }
    
    $('.content').each(function() {
    
        var markdownable = $(this).html(),
            content = markdown(markdownable);
    
        $(this).html(content);
    
    
    });
    

    working jsfiddle example:-

    http://jsfiddle.net/dwxmjkb3/2/

    new Code as per request:-

    function markdown(markdownableOrg) {
        var bold = /\*\*(\S(.*?\S)?)\*\*/gm;
        var dataArray = markdownableOrg.split("\n");
        var data = [];
        for (var i = 0; i < dataArray.length; i++) {
            var markdownable = dataArray[i];
            markdownable = markdownable.replace(bold, '<span style="font-weight:bold">$1</span>');
            if (markdownable.indexOf("&gt;") == 0) {
                markdownable = markdownable.replace("&gt;", "<blockquote>");
                markdownable += "</blockquote>";
            }
            data.push(markdownable)
        }
    
        return data.join("\n");
    }
    

    now above given method splits the data(each line) and checks for > and replace it with blockquote.

    updated jsfiddle :-http://jsfiddle.net/dwxmjkb3/6/

    thanks