Last active
June 22, 2021 03:01
-
-
Save skorotkiewicz/bc3f4bd0ff5333d5566bf8a13c9f50ab to your computer and use it in GitHub Desktop.
React Linkify - Simple Create Clickable Hashtags, Mentions etc...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createElement } from "react" | |
export const parser = (text) => { | |
let hashtag = /(#[\w]+)/g // parse: #test | |
let user = /(\^[\w]+)/g // parse: ^test | |
let blog = /(\/s\/[\d]+)/g // parse: /s/123 | |
let url = /(\b(https?):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi | |
return text.split(hashtag).map((chunk) => { | |
return chunk.split(user).map((chunk) => { | |
return chunk.split(blog).map((chunk) => { | |
return chunk.split(url).map((chunk) => { | |
if (chunk.match(hashtag)) { | |
return createElement("a", { href: `/tags/${chunk.replace("#", "")}` }, chunk) | |
} | |
if (chunk.match(user)) { | |
return createElement("a", { href: `/blog/${chunk.replace("^", "")}` }, chunk) | |
} | |
if (chunk.match(blog)) { | |
return createElement("a", { href: chunk }, " [blog] ") | |
} | |
if (chunk.match(url)) { | |
return createElement("a", { href: chunk }, " [link] ") | |
// return createElement("a", { href: chunk }, chunk) | |
} | |
if (chunk === "http" || chunk === "https") { | |
return "" | |
} | |
return chunk | |
}) | |
}) | |
}) | |
}) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { parser } from "parseHashtags.js" | |
parser(text) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment