target-blankify
v1.0.1
Published
A TypeScript utility that automatically adds target="_blank" to all <a> tags in HTML strings
Downloads
7
Maintainers
Readme
🎯 target-blankify
A lightweight TypeScript utility that automatically adds target="_blank" to all <a> tags in your HTML string, with security best practices built-in.
✨ Features
- 🔄 Automatically adds
target="_blank"to all links - 🛡️ Includes
rel="noopener noreferrer"for security - ⚡ Lightweight and fast
- 🔍 Domain exclusion support
- 📦 Written in TypeScript
- ✅ Fully tested
🚀 Installation
npm install target-blankify💡 Usage
import { targetBlankify } from "target-blankify";
// Basic usage
const htmlString = '<a href="https://example.com">Click here</a>';
const updatedHtml = targetBlankify(htmlString);
// Output: <a href="https://example.com" target="_blank" rel="noopener noreferrer">Click here</a>
// With options
const options = {
exclude: ["example.com"], // Links to example.com won't get target="_blank"
rel: "noopener", // Custom rel attribute
};
const updatedHtmlWithOptions = targetBlankify(htmlString, options);⚙️ Options
| Option | Type | Default | Description |
| --------- | ---------- | ----------------------- | ---------------------------------------------------------- |
| exclude | string[] | [] | Array of domains to exclude from getting target="_blank" |
| rel | string | "noopener noreferrer" | Custom rel attribute value |
🔒 Security
This library automatically adds rel="noopener noreferrer" to all links with target="_blank" to prevent potential security vulnerabilities. You can customize this behavior using the rel option.
📝 Examples
Basic Usage
const html = '<a href="https://example.com">Click here</a>';
const result = targetBlankify(html);
// <a href="https://example.com" target="_blank" rel="noopener noreferrer">Click here</a>Excluding Domains
const html = `
<a href="https://example.com">Internal link</a>
<a href="https://external.com">External link</a>
`;
const result = targetBlankify(html, { exclude: ["example.com"] });
// Only the external link gets target="_blank"Custom Rel Attribute
const html = '<a href="https://example.com">Click here</a>';
const result = targetBlankify(html, { rel: "noopener" });
// <a href="https://example.com" target="_blank" rel="noopener">Click here</a>🧪 Testing
npm test📝 License
MIT
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
🙏 Acknowledgments
- Inspired by the need to automatically make external links open in new tabs
- Built with TypeScript for type safety
- Tested with Jest for reliability
