Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using js regex to replace simple markup styles like **bold** to <b>bold</b>

I'm trying to take a chunk of plain text and convert parts of it into html tags. I don't need a full rich editor, just these few tags:

**bold**
__underline__
~~italics~~
--strike--
<<http://www.link.com>>

This is the method I have attempted to write but my lack of regex/js seems to be holding it back:

function toMarkup($this) {
    var text = $this.text();
    text = text.replace("\*\*(.*)\*\*", "<b>$1</b>");
    text = text.replace("__(.*)__", "<u>$1</u>");
    text = text.replace("~~(.*)~~", "<i>$1</i>");
    text = text.replace("--(.*)--", "<del>$1</del>");
    text = text.replace("<<(.*)>>", "<a href='$1'>Link</a>");
    $this.html(text);
}

Any glaring errors as to why these replaces are not working? Another issue I'm just now realizing is by converting this text to html I am unescaping any other potential tags that may be malicious. A bonus would be any advice on how to only escape these elements and nothing else.

like image 719
ant-depalma Avatar asked Jun 05 '13 18:06

ant-depalma


1 Answers

First of all, they are just string, not regexs. Secondly you should use not-greedy .*.

Also, you may want to use the g modifier to match every occourrence in the text.

function toMarkup($this) {
    var text = $this.text();
    text = text.replace(/\*\*(.*?)\*\*/g, "<b>$1</b>");
    text = text.replace(/__(.*?)__/g, "<u>$1</u>");
    text = text.replace(/~~(.*?)~~/g, "<i>$1</i>");
    text = text.replace(/--(.*?)--/g, "<del>$1</del>");
    text = text.replace(/<<(.*?)>>/g, "<a href='$1'>Link</a>");
    $this.html(text);
}
like image 140
n1xx1 Avatar answered Sep 19 '22 10:09

n1xx1