0
# LinkifyIt
1
2
LinkifyIt is a links recognition library with full Unicode support for detecting high-quality link patterns in plain text. It supports international domains, astral characters, fuzzy link detection without protocols, and provides extensible rules with custom normalizers for specialized link types.
3
4
## Package Information
5
6
- **Package Name**: linkify-it
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install linkify-it`
10
11
## Core Imports
12
13
```javascript
14
import LinkifyIt from "linkify-it";
15
16
// Can also import as default function
17
import linkify from "linkify-it";
18
```
19
20
For CommonJS:
21
22
```javascript
23
const LinkifyIt = require("linkify-it");
24
```
25
26
## Basic Usage
27
28
```javascript
29
import LinkifyIt from "linkify-it";
30
31
// Create linkifier instance (works with or without 'new')
32
const linkify = LinkifyIt();
33
34
// Test if text contains links
35
const hasLinks = linkify.test("Visit github.com!");
36
// => true
37
38
// Extract all links from text
39
const matches = linkify.match("Visit github.com and https://example.com");
40
// => [{schema: "", index: 6, lastIndex: 16, raw: "github.com", text: "github.com", url: "http://github.com"},
41
// {schema: "https:", index: 21, lastIndex: 42, raw: "https://example.com", text: "https://example.com", url: "https://example.com"}]
42
43
// Configure fuzzy detection options
44
linkify.set({ fuzzyIP: true, fuzzyEmail: true });
45
46
// Add custom protocols
47
linkify.add("git:", "http:"); // Alias git: to http:
48
linkify.add("ftp:", null); // Disable ftp: protocol
49
```
50
51
## Architecture
52
53
LinkifyIt is built around several key components:
54
55
- **LinkifyIt Constructor**: Main factory function creating linkifier instances with configurable schemas and options
56
- **Detection Engine**: Pattern matching system using compiled regexes for efficient link recognition
57
- **Schema System**: Extensible protocol definitions supporting custom validators and normalizers
58
- **Match Objects**: Structured results containing link metadata, positions, and normalized URLs
59
- **Unicode Support**: Full unicode character class handling including astral characters via uc.micro dependency
60
61
## Capabilities
62
63
### LinkifyIt Constructor
64
65
Creates new linkifier instance with optional additional schemas and configuration options.
66
67
```javascript { .api }
68
/**
69
* Creates new linkifier instance with optional additional schemas.
70
* Can be called without `new` keyword for convenience.
71
* @param schemas - Optional object with protocol definitions (prefix/validator pairs)
72
* @param options - Optional configuration options for fuzzy link detection
73
* @returns LinkifyIt instance
74
*/
75
function LinkifyIt(schemas?: Record<string, string | SchemaDefinition>, options?: LinkifyItOptions);
76
77
interface LinkifyItOptions {
78
/** Recognize URLs without http(s):// prefix. Default true */
79
fuzzyLink?: boolean;
80
/** Allow IPs in fuzzy links. Can conflict with version numbers. Default false */
81
fuzzyIP?: boolean;
82
/** Recognize emails without mailto: prefix. Default true */
83
fuzzyEmail?: boolean;
84
/** Terminate links with --- (long dash). Default false */
85
"---"?: boolean;
86
}
87
88
interface SchemaDefinition {
89
/** Validator function or RegExp to check tail after link prefix */
90
validate: ((text: string, pos: number, self: LinkifyIt) => number) | RegExp;
91
/** Optional function to normalize text & url of matched result */
92
normalize?: (match: Match, self: LinkifyIt) => void;
93
}
94
```
95
96
### Link Detection Methods
97
98
Core methods for detecting and extracting links from text.
99
100
```javascript { .api }
101
/**
102
* Searches linkifiable pattern and returns true on success or false on fail
103
* @param text - Text to search for links
104
* @returns Boolean indicating if link was found
105
*/
106
test(text: string): boolean;
107
108
/**
109
* Quick check if link MAY exist. Can give false positives but no false negatives.
110
* Used for speed optimization when you need to check that link NOT exists.
111
* @param text - Text to check
112
* @returns Boolean indicating if link might exist
113
*/
114
pretest(text: string): boolean;
115
116
/**
117
* Returns array of found link matches or null if nothing found
118
* @param text - Text to scan for links
119
* @returns Array of Match objects or null
120
*/
121
match(text: string): Match[] | null;
122
123
/**
124
* Returns fully-formed (not fuzzy) link if it starts at the beginning
125
* of the string, and null otherwise. Doesn't work with fuzzy links.
126
* @param text - Text to check
127
* @returns Match object or null
128
*/
129
matchAtStart(text: string): Match | null;
130
131
/**
132
* Similar to test() but checks only specific protocol tail exactly at given position
133
* @param text - Text to scan
134
* @param schema - Schema/protocol name to test
135
* @param position - Text offset to check from
136
* @returns Length of found pattern (0 on fail)
137
*/
138
testSchemaAt(text: string, schema: string, position: number): number;
139
```
140
141
### Configuration Methods
142
143
Chainable methods for configuring linkifier behavior and adding custom rules.
144
145
```javascript { .api }
146
/**
147
* Add new rule definition or disable existing rule
148
* @param schema - Rule name (protocol prefix like 'skype:')
149
* @param definition - Schema definition, alias string, or null to disable
150
* @returns this (chainable)
151
*/
152
add(schema: string, definition: string | SchemaDefinition | null): LinkifyIt;
153
154
/**
155
* Set recognition options for links without schema
156
* @param options - Options object with fuzzyLink, fuzzyEmail, fuzzyIP properties
157
* @returns this (chainable)
158
*/
159
set(options: Partial<LinkifyItOptions>): LinkifyIt;
160
161
/**
162
* Load or merge new tlds list for fuzzy links (without schema) to avoid false positives
163
* @param list - TLD list to add (array or single string)
164
* @param keepOld - Whether to merge with current list (default false)
165
* @returns this (chainable)
166
*/
167
tlds(list: string | string[], keepOld?: boolean): LinkifyIt;
168
```
169
170
### Extensibility Methods
171
172
Methods for customizing link processing and regex compilation.
173
174
```javascript { .api }
175
/**
176
* Default normalizer for matches (can be overridden)
177
* Adds http:// prefix for fuzzy links and mailto: for emails
178
* @param match - Match object to normalize
179
*/
180
normalize(match: Match): void;
181
182
/**
183
* Override hook called during regex compilation
184
* Can be used to modify basic RegExp patterns
185
*/
186
onCompile(): void;
187
```
188
189
## Types
190
191
### Match Object
192
193
Result object representing a single detected link.
194
195
```javascript { .api }
196
interface Match {
197
/** Prefix (protocol) for matched string, can be empty for fuzzy links */
198
schema: string;
199
/** First position of matched string */
200
index: number;
201
/** Next position after matched string */
202
lastIndex: number;
203
/** Original matched text */
204
raw: string;
205
/** Normalized text of matched string */
206
text: string;
207
/** Normalized URL of matched string */
208
url: string;
209
}
210
```
211
212
### Schema Definition Types
213
214
```javascript { .api }
215
interface SchemaDefinition {
216
validate: ValidatorFunction | RegExp;
217
normalize?: NormalizerFunction;
218
}
219
220
type ValidatorFunction = (text: string, pos: number, self: LinkifyIt) => number;
221
type NormalizerFunction = (match: Match, self: LinkifyIt) => void;
222
```
223
224
## Usage Examples
225
226
### Custom Protocol Handler
227
228
```javascript
229
import LinkifyIt from "linkify-it";
230
231
const linkify = LinkifyIt();
232
233
// Add Twitter mention handler
234
linkify.add("@", {
235
validate: function (text, pos, self) {
236
const tail = text.slice(pos);
237
238
if (!self.re.twitter) {
239
self.re.twitter = new RegExp(
240
"^([a-zA-Z0-9_]){1,15}(?!_)(?=$|" + self.re.src_ZPCc + ")"
241
);
242
}
243
244
if (self.re.twitter.test(tail)) {
245
// Prevent @@mention (invalid)
246
if (pos >= 2 && text[pos - 2] === "@") {
247
return 0;
248
}
249
return tail.match(self.re.twitter)[0].length;
250
}
251
return 0;
252
},
253
normalize: function (match) {
254
match.url = "https://twitter.com/" + match.url.replace(/^@/, "");
255
}
256
});
257
258
const matches = linkify.match("Hello @username!");
259
// => [{schema: "@", ..., text: "@username", url: "https://twitter.com/username"}]
260
```
261
262
### TLD Management
263
264
```javascript
265
import LinkifyIt from "linkify-it";
266
import tlds from "tlds"; // Full TLD list package
267
268
const linkify = LinkifyIt();
269
270
// Add custom TLD while keeping defaults
271
linkify.tlds("onion", true);
272
273
// Replace with full TLD list
274
linkify.tlds(tlds);
275
276
// Test custom domains
277
console.log(linkify.test("visit example.onion")); // true with custom TLD
278
console.log(linkify.test("check example.xyz")); // true with full TLD list
279
```
280
281
### Advanced Configuration
282
283
```javascript
284
import LinkifyIt from "linkify-it";
285
286
// Create with custom options
287
const linkify = LinkifyIt({
288
fuzzyLink: true,
289
fuzzyEmail: true,
290
fuzzyIP: true,
291
"---": true // Terminate links at triple dash
292
});
293
294
// Add Git protocol as HTTP alias
295
linkify.add("git:", "http:");
296
297
// Disable FTP support
298
linkify.add("ftp:", null);
299
300
// Test various link types
301
console.log(linkify.match("git://github.com/user/repo.git"));
302
console.log(linkify.match("Contact me at user@domain.com"));
303
console.log(linkify.match("Server at 192.168.1.1:8080"));
304
```
305
306
## Error Handling
307
308
- Constructor throws `Error` for invalid schema definitions during `.add()` calls
309
- Detection methods (`test`, `match`, `pretest`, etc.) return `null`, `false`, or `0` for no matches rather than throwing
310
- Schema validation errors throw `Error` with descriptive messages like `"(LinkifyIt) Invalid schema 'name': reason"`
311
- Invalid normalizer functions throw `Error` during schema compilation via `.add()`
312
- The `tlds()` method accepts arrays or single strings without throwing for invalid input types