1

I need to convert some string to html. Just like this

let str = 'lorem ipsum [google website]="https://google.com" lorem ipsum [facebook website]="https://facebook.com"'

convert(str)

expected output:

lorem ipsum <a href="https://google.com">google website</a> lorem ipsum <a href="https://facebook.com">facebook website</a>

P.S i'm using reactjs

2 Answers2

2

You can use the regular expressions and string.replace(regex, replaceWith). $1, $2 are capture groups (see MDN docs)

let re = /\[(.+?)\]="(.+?)"/g
let str = 'lorem ipsum [google website]="https://google.com" lorem ipsum [facebook website]="https://facebook.com"';
let newStr = str.replace(re, '<a href="$2">$1</a>');
document.write(newStr);
Vlad
  • 628
  • 8
  • 19
0

Try this, this will only match valid url:

function convert(string){
  console.log(string.replace(/\[([^\]]*)\]="((https?|ftp):\/\/(-\.)?([^\s/?\.#-]+\.?)+(\/[^\s]*)?)"/ig, "<a href='\$2'>$1</a>"));
}
convert('lorem ipsum [google]=https://google.com lorem ipsums lorem [facebook]=https://facebook.com ipsum lorem')
Illya
  • 1,264
  • 1
  • 3
  • 15