-1

here is my string

var text = "Lorem ipsum dolor *https://www.google.com/* amet, *https://www.google.com/*";

I would like to create new one like this

var newText = "Lorem ipsum dolor <a href="https://www.google.com/">https://www.google.com/</a> amet, <a href="https://www.google.com/">https://www.google.com/</a>";

My script not works. What I'm doing wrong?

var newText = text.replace("*", "<a href=></a>");
Dexygen
  • 12,287
  • 13
  • 80
  • 147
user7376146
  • 63
  • 1
  • 5

2 Answers2

1

You are replacing the first occurence of the asterix with <a href=></a>

var text = "Lorem ipsum dolor *https://www.google.com/* amet, *https://www.google.com/*";
var newText = text.replace("*", "<a href=></a>");
console.log(newText);

To replace them all, you could use a capturing group (which will be in $1) and then use replace:

\*(.*?)\*

Explanation

  • Match an asterix \*
  • A capturing group which captures any character non greedy (.*?)
  • Match an asterix \*

var text = "Lorem ipsum dolor *https://www.google.com/* amet, *https://www.google.com/*";
var newText = text.replace(/\*(.*?)\*/g, "<a href=\"$1\">$1</a>");
console.log(newText)
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
1

You could try the code below:

var text = "Lorem ipsum dolor *https://www.google.com/* amet, *https://www.google.com/*";
var arrtext=text.split('*');
var newtext='';

for(var i=0;i<arrtext.length;i++){

    if(arrtext[i].startsWith("http")){
         var link='<a href="'+arrtext[i]+'">'+arrtext[i]+'</a>';
         newtext=newtext+link;
    }else{
        newtext=newtext+arrtext[i];
    }

}