I’m sanitizing CDATA content from various third-party XML feeds, stripping all HTML server-side and using Linkify.js.org (v3.0.3) to safely reapply HTML tags to the sanitized plaintext links client-side.
My project relies a lot on jQuery (v3.6.0).
The linkify jQuery DOM Data API is working great on links and email addresses, but hashtags are proving problematic. By default, hashtags redirect to https://my-domain.com/current-dir/#<HashTag>
, but I’d like them to redirect to https://twitter.com/hashtag/<HashTag>
. I know this is possible from the demo examples, but I’d like to stick with a jQuery solution, and maintain the div data attributes if possible.
I’ve read the documentation from Linkify.js.org/docs/ but can’t figure out how to change the hashtag URL without dropping the jQuery div data attributes.
Below is a simple example (it’s important I maintain a _blank
HREF target):
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Linkify</title>
</head>
<body>
<div data-linkify="this" data-linkify-target="_blank">
Domain Test: domain.com. Email Test: [email protected]. HashTag Test: #Linkify.
</div>
<script src="/js/jquery.min.js"></script>
<script src="/js/linkify.min.js"></script>
<script src="/js/linkify-jquery.min.js"></script>
<script src="/js/linkify-plugin-hashtag.min.js"></script>
</body>
</html>
Work’s great, but as mentioned, #Linkify redirects to the same page (e.g; https://my-domain.com/current-dir/#Linkify
).
Client-side JS is not my strong point, but is there a data-linkify
attribute I can use to change the HashTag destination to Twitter? Or additional jQuery code I can use to modify the behaviour of the linkify-plugin-hashtag.min.js
plugin?
2
Answers
Use the hashtag plugin options… And since you do not want to call linkify directly, you’ll need to play with the default options.
If you add this, it should work out.
You can read more at https://linkify.js.org/docs/plugin-hashtag.html and https://linkify.js.org/docs/options.html
Add the following code to your HTML after
<script src="/js/linkify-plugin-hashtag.min.js"></script>
:This is a modification to @Salketer’s code that should make this work with the latest version of Linkify.