i have a simple replace function that replaces urls like
http://www.example.com to <a href="www.example.com">http://www.example.com</a>
given below
text = text.replace(/(\s|>|^)(https?:[^\s<]*)/igm,'$1<a href="$2" class="oembed" >$2</a>');
text = text.replace(/(\s|>|^)(mailto:[^\s<]*)/igm,'$1<a href="$2" class="oembed" target="_blank">$2</a>');
The problem is that it wraps urls inside anchor tags as well and i have to give html as input so help me out with the regexp to ignore wraping anchor tag for urls already having an anchor tag
Well if you are creating urls one by one and appending to dom right after you create them then you can try something like
var url = $('a[href="url you are about to create"]');
if(url== undefined)
// url does not exist, create.
else
//already added, ignore
If you are using jQuery you can try the following method which ignores all the elements( including a
elements ) and wraps the textNodes that match the regex.
var url = /(http|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?/gi;
var mailto = /(mailto:[a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/gi;
str = $('<div>').html(str).contents().each(function () {
if (this.nodeType === 3) { // if node is a textNode
$(this).replaceWith(function () {
return this.nodeValue.replace(url, function (m) {
return '<a href="' + m + '" class="oembed">' + m + '</a>';
}).replace(mailto, function(m) {
return '<a href="' + m + '" class="oembed" target="_blank">' + m + '</a>';
});
})
}
}).end().html();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.