Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace string with html tag [closed]

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

like image 572
Shotiko Topchishvili Avatar asked Sep 06 '25 02:09

Shotiko Topchishvili


2 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>
like image 197
caramba Avatar answered Sep 07 '25 21:09

caramba


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))
like image 34
Ghoul Ahmed Avatar answered Sep 07 '25 21:09

Ghoul Ahmed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!