Reputation: 229
How can I make as link from a url found in text, but excluding any already made link found? Can you help with the proper regex?
function makeurl(text) {
var urlRegex = /(https?:\/\/[^\s]+)/g;
return text.replace(urlRegex, function(url) {
return '<a href="' + url + '">' + url + '</a>';
})
}
var check = 'Hello <a href="https://www.xyyyyy.co">cick here</a> to visit our website http://google.x';
console.log (makeurl(check) )
https://jsfiddle.net/9L30zotx/
I want to change only http://google.x but leave as is the already made html for www.xyyyyy.co
Upvotes: 1
Views: 411
Reputation: 5586
If the anchor text isn't a url itself, then you can easily parse out the HTML content, and then you'll have only pure text.
Try the following code,
function makeurl(text) {
var urlRegex = /(https?:\/\/[^\s]+)/g;
document.body.innerHTML = text; // taking document.body as example
text = document.body.innerText;
return text.replace(urlRegex, function(url) {
return '<a href="' + url + '">' + url + '</a>';
});
}
var check = 'Hello <a href="https://www.xyyyyy.co">click here</a> to visit our website http://google.x';
console.log(makeurl(check))
Upvotes: 0
Reputation: 11
Maybe you can check if there is a space before the link (or the start in case the link is at the beginning of the text) using ([\s]|^)
at the beginning of your regex (/([\s]|^)(https?:\/\/[^\s]+)/g
).
Upvotes: 1