I have a simple CMS I built for a client of mine.
This issue is, instead of him posting links probably through anchor tags, he just copies and pastes it straight into the text editor.
Is there a way that these links can be wrapped in an anchor tag using JavaScript? So when the page loads instead of it looking link this:
It will look like this
<a href="; target="_blank">;/a>
Stack Overflow actually does this when a user posts a URL to an answer/question (if that helps understand what I am trying to achieve).
I have a simple CMS I built for a client of mine.
This issue is, instead of him posting links probably through anchor tags, he just copies and pastes it straight into the text editor.
Is there a way that these links can be wrapped in an anchor tag using JavaScript? So when the page loads instead of it looking link this:
http://google.
It will look like this
<a href="http://google." target="_blank">http://google.</a>
Stack Overflow actually does this when a user posts a URL to an answer/question (if that helps understand what I am trying to achieve).
Share Improve this question edited Aug 10, 2021 at 0:45 Peter Mortensen 31.6k22 gold badges110 silver badges133 bronze badges asked Oct 21, 2013 at 0:06 Peter StuartPeter Stuart 2,4447 gold badges45 silver badges74 bronze badges 3- It's a simple string concatenation. Have you tried anything you can post here for us to look at? – user2625787 Commented Oct 21, 2013 at 0:08
- I am not quite sure where to start. I read one post here, but it seems to affect URLs within script tags and embedded tags. – Peter Stuart Commented Oct 21, 2013 at 0:12
- 1 stackoverflow./questions/6168260/how-to-parse-a-url stackoverflow./questions/579335/… stackoverflow./questions/247479/jquery-text-to-link-script – scrowler Commented Oct 21, 2013 at 0:17
1 Answer
Reset to default 5You could try something along these lines. Decorate the tags where you want these replacements to take effect with a custom attribute like data-linkify
:
<div data-linkify>something http://google. something</div><div linkify>something</div>
Now perform replacements inside any element with data-linkify
set.
$('*[data-linkify]').each(function() {
$(this).html($(this).html().replace(/(?:(https?\:\/\/[^\s]+))/m, '<a href="$1">$1</a>'));
});
There are some caveats. This isn’t a great regex at all — it simply matches anything starting with http://
or https://
up until the first whitespace character. Look for a better URL matching regex.
Also, the use of replace against .html()
means that it will break any existing links that happen to fall under your data-linkify
elements! If there happen to be doublequote characters in your textual links, it will create broken anchor elements.
You might consider a very simple markup of some sort to identify links — it would be much better than guessing.