Skip to content

Instantly share code, notes, and snippets.

@skorotkiewicz
Last active June 22, 2021 03:01
Show Gist options
  • Save skorotkiewicz/bc3f4bd0ff5333d5566bf8a13c9f50ab to your computer and use it in GitHub Desktop.
Save skorotkiewicz/bc3f4bd0ff5333d5566bf8a13c9f50ab to your computer and use it in GitHub Desktop.
React Linkify - Simple Create Clickable Hashtags, Mentions etc...
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
})
})
})
})
}
import { createElement } from "react"
export const parser = (text) => {
let hashtag = /(#[\w]+)/g
return text.split(hashtag).map((chunk) => {
if (chunk.match(hashtag)) {
return createElement("a", { href: `/tags/${chunk.replace("#", "")}` }, chunk)
}
return chunk
})
}
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