-1

[http://url.com](Here is a link to explain.)

What regex would replace this with:

<a href="http://url.com">Here is a link to explain.</a>?

str.replace(/\[(\b(https?):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])\]/ig, "<a href='$1'>$1</a>")

This makes [http://url.com] become a link with http://url.com as the text, but I need to have the text be replaced inside ().

user1063287
  • 10,265
  • 25
  • 122
  • 218
frosty
  • 2,779
  • 6
  • 34
  • 63
  • You seem to be interested in converting several markdown style strings to HTML based on your other questions. Why not just use a markdown parser library? – Joseph Marikle Jul 02 '15 at 18:29
  • I don't know what to search for / how to use such a thing – frosty Jul 02 '15 at 18:30
  • 2
    marked.js is a nice one it appears: https://github.com/chjj/marked. Here's a quick example usage: http://jsfiddle.net/jmarikle/07ozc5df/ – Joseph Marikle Jul 02 '15 at 18:33
  • 1
    Note that in that demo the link works. It's just that jsfiddle blocks the navigation it seems. – Joseph Marikle Jul 02 '15 at 18:35
  • That looks really useful, I'll try it out. – frosty Jul 02 '15 at 18:36
  • 1
    Well that's by far the most useful thing I've discovered tonight. Thank you so much! Saved me a lot of trouble and question-asking. – frosty Jul 02 '15 at 18:40
  • @JosephMarikle I can't seem to find any info on all the different options? For example how to do underline and strikethrough. – frosty Jul 02 '15 at 19:32
  • Underline is a unique circumstance (see here: http://programmers.stackexchange.com/questions/207727/why-there-is-no-markdown-for-underline). For strikethrough and other syntaxes, [this link](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) seems to be a good resource. – Joseph Marikle Jul 02 '15 at 19:39

1 Answers1

2

This will match those and extract each part as separate matches:

/\[(.*)\]\((.*)\)/

var regex = /\[(.*)\]\((.*)\)/,
    matches = regex.exec('[http://url.com](This is the text)');
document.querySelector('pre').innerText += matches[1] + '\n' + matches[2];

// create a link
var linkText = '<a href="' + matches[1] + '">' + matches[2] + '</a>';
document.querySelector('pre').innerText += '\n' + linkText;
<pre></pre>
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91