Reputation:
I have the following list
<li class='lists'>Sonata</li>
<li class='lists'>http://facebook.com</li>
<li class='lists'>Omega</li>
<li class='lists'>Rule of Thumb</li>
<li class='lists'>https://youtube.com</li>
I want to wrap only the text that contains http://
or https://
with the URL link. So, what I am doing currently in jQuery is:
if ($('li.lists:contains(http://)') || ('li.lists:contains(https://)')) {
$('li.lists:contains(http://)').wrapInner(function () {
return "<a href='" + $(this).text() + "'></a>";
});
$('li.lists:contains(https://)').wrapInner(function () {
return "<a href='" + $(this).text() + "'></a>";
});
}
As you can see, just for one character s
in link, I have to use or ||
statement and call the wrapInner()
function twice.
Is it possible to acheive this with Regular Expression in jQuery with one liners like
if ($('li.lists:contains(http/?s/://)')) {
OR
$('li.lists:contains(http/?s/://)')
something like this.
JsFiddle for the above codes.
Upvotes: 0
Views: 398
Reputation: 57095
$('li.lists').html(function (_, html) {
return html.replace(/((?:http|https):\/\/.+)$/g, '<a href="$1">$1</a>');
});
var urlPattern = new RegExp("(http|https)://");
$('li.lists').filter(function (_, str) {
return urlPattern.test(str.innerHTML);
}).wrapInner(function () {
return "<a href='" + $(this).text() + "'></a>";
});
Upvotes: 1