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
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With