How to replace string with html tag

Viewed 123

i am trying to find some regex which will replace part of a string with html tags. Part of String which should get replaced looks like this: lorem Google=https://google.com ipsum

Excpected output: lorem <a href="https://google.com">Google</a> ipsum

P.S i'm using reactjs

4 Answers

var string = "Google=https://google.com";

var regex = /(\w*)=(https?\:\/\/\w*\.\w*)/gm;

var regexResult = regex.exec(string);

var newAtag = document.createElement('a');
newAtag.href = regexResult[2];
newAtag.innerHTML = regexResult[1];

console.log(newAtag);

document.body.appendChild(newAtag);

Updated based on your comment how to do it if the string is "lorem Google=https://google.com ipsum" basically exactly the same as above. Just don't touch anything before and after the matching regex part. See this:

var element = document.querySelector('div');
var string = element.innerHTML;

var regex = /(\w*)=(https?\:\/\/\w*\.\w*)/gm;

var regexResult = regex.exec(string);

var newAtag = document.createElement('a');
newAtag.href = regexResult[2];
newAtag.innerHTML = regexResult[1];
console.log(newAtag);

element.innerHTML = string.replace(regex, newAtag.outerHTML);
<div>lorem Google=https://google.com ipsum</div>

try this

const ch = "Google=https://google.com"
const makeUrl = ch => {
  const [name, url] = ch.split(/=/)
  return `<a href="${url}">${name}</a>`
}

console.log(makeUrl(ch))

I suggest using a tool like RegEx101 to create and test the RegEx:

https://regex101.com/r/BSsJei/6

JavaScript example

var str=`# Expect (partially) valid
lorem Google=https://www.google.com ipsum
lorem Google=http://google.com
https://google.com

Long text with linebreaks - http://test.test with many links http://test.test
xxx http://test.TEST xxx https://www.subdomain.google.com.

# Correctly matched yet wrong URLs
https://www.google

# Expect invalid
http://googlecom
htt://google.com
xxx`;

var regEx = /https?:\/\/((\w+\.){1,2})?(\w+\.)\w+/gi;
var result = str.match(regEx);

console.log(result);

This will give you an array with all matched URLs that you then can easily replace with HTML tags.

The RegEx pattern is designed to work with common URLs, yet I did not test it with more complex patterns. It still should be good enough for practical use.


Pattern explained

  • Match either http/https
  • Check for 0-2 subdomains (e.g. www.domain, www.subdomain.domain)
  • Check for domain name

You can use the link function of javascript, It will work fine and much mere readable

const link = "Google=https://google.com"
const generateLink = link => {
  const [name, url] = link.split(/=/)
  return "Google".link(url)
}

console.log(generateLink (link))
Related