-
Notifications
You must be signed in to change notification settings - Fork 0
/
RichTextConvertor.js
65 lines (57 loc) · 1.88 KB
/
RichTextConvertor.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class RichTextConverter {
constructor(config = {}) {
// Default configurations
this.config = {
hashtags: {
pattern: /#(\w+)/g,
url: 'https://example.com/tags/$1',
},
mentions: {
pattern: /@(\w+)/g,
url: 'https://example.com/profiles/$1',
},
bold: {
pattern: /\*\*(.*?)\*\*/g,
replace: '<strong>$1</strong>',
},
underline: {
pattern: /__(.*?)__/g,
replace: '<u>$1</u>',
},
...config, // Merge with user provided configurations
};
}
convert(text) {
let convertedText = text;
// Convert hashtags to links
if (this.config.hashtags && this.config.hashtags.pattern) {
const { pattern, url } = this.config.hashtags;
convertedText = convertedText.replace(pattern, `<a href="${url}">#$1</a>`);
}
// Convert mentions to links
if (this.config.mentions && this.config.mentions.pattern) {
const { pattern, url } = this.config.mentions;
convertedText = convertedText.replace(pattern, `<a href="${url}">@$1</a>`);
}
// Apply other Markdown styles
if (this.config.bold && this.config.bold.pattern) {
const { pattern, replace } = this.config.bold;
convertedText = convertedText.replace(pattern, replace);
}
if (this.config.underline && this.config.underline.pattern) {
const { pattern, replace } = this.config.underline;
convertedText = convertedText.replace(pattern, replace);
}
return convertedText;
}
}
// Export RichTextConverter for use in Node.js or CommonJS environments
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
module.exports = RichTextConverter;
}
// For use in browser or with AMD style loaders like RequireJS
if (typeof define === 'function' && define.amd) {
define('RichTextConverter', [], function () {
return RichTextConverter;
});
}