JSFiddle - React, Tailwind, and code Playground

by fliptheweb

JavaScript

const links = [
	{
    linkTitle: 'test link',
    url: 'ya.ru'
  },
  {
    linkTitle: 'another link',
    url: 'ya2.ru'
  },
]

const text = "That's a text with test link and maybe another link"

// Build regexp for all our links like (linktext|linktext2)
const linksPattern = new RegExp(`(${links.map(({linkTitle}) => linkTitle).join('|')})`)

let result = text.split(linksPattern).map((textChunk, i) => {
	const link = links.find(({linkTitle}) => linkTitle === textChunk)
  if (!link) return textChunk
  // You could return react element as well
  return `<a href="${link.url}">${link.linkTitle}</a>`
})

document.body.innerHTML = result.join('')