user1775888 user1775888 - 5 months ago 25
jQuery Question

regex to add `//` before hyperlinks

I use the below function to wrap/parse links in a string with an

a
tag.
This supports plain links in a string, but also markdown notation, like
[title](link)
.

But I have a problem: how to fill
//
in the href attribute, when the link doesn't have
//
?

Test data:

google.com // ok: leave this as is
www.google.com // error: need to add `//` in href value
http://google.com // ok
http://www.google.com // ok
[google](google.com) // error: need to add `//` in href value
[google](www.google.com) // error: need to add `//` in href value
[google](http://google.com) // error: need to add `//` in href value


See JS fiddle



var markdownParse = (function() {

return {
autoLinks: function(text, options) {
var simpleURLRegex = /\b(((https?|ftp|dict):\/\/|www\.)[^'">\s]+\.[^'">\s]+)(?=\s|$)(?!["<>])/gi;
text = text.replace(simpleURLRegex, '<a href=\"$1\">$1</a>');
return text;
},
stripLinkDefinitions: function(text) {
text = text.replace(/\[(.*?)\]\((.*?)\)/gi, '<a href="$2">$1</a>');
return text;
},
}
})();

$('.convert').on('click', function() {
var inputVal = $('.input').val();

inputVal = markdownParse.autoLinks(inputVal);
inputVal = markdownParse.stripLinkDefinitions(inputVal);

$('.output').html(inputVal)
});

.convert {
cursor: pointer;
}
.output {
white-space: pre;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


<textarea class="input"></textarea>

<div class="output"></div>

<div class="convert">convert</div>




Answer

You could use the replace method with a callback function. That function could then add the http:// prefix if it is not there yet.

By using a callback you can also treat both cases in one regexp replace call:

var markdownParse = (function() {
  return {
    autoLinks: function(text, options) {
      var simpleURLRegex = /\[(.*?)\]\((.*?)\)|\b((https?|ftp|dict):\/\/|www\.)[^'">\s]+\.[^'">\s]+(?=\s|$)(?!["<>])/gi;
	  return text.replace(simpleURLRegex, function (all, name, url) {
		url = url || all;
		if (url.indexOf('://') === -1) url = 'http://' + url;
		return '<a href="' + url +  '">' + (name || all) + '</a>';
	  });
    },
  }
})();

$('.convert').on('click', function() {
	var inputVal = $('.input').val();
    inputVal = markdownParse.autoLinks(inputVal);
    $('.output').html(inputVal);
    $('.outHTML').text(inputVal);
});
.input {
    width: 100%;
	height: 70px;
}
.output, .outHTML {
	white-space:pre;
    margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="input">You can reach google.com via www.google.com or even
http://google.com and http://www.google.com. Put it like 
[google](google.com) or like [google](www.google.com) or like [google](http://google.com).
</textarea><br>
<button class="convert">Convert</button>
<div class="output"></div>
<div class="outHTML"></div>

Comments