1

I use a regex convert <a> with images url to <img>

var message='<a href="http://example.com/example.jpg" target="_blank" rel="noopener noreferrer">http://example.com/example.jpg</a>';
message.replace(/<a.*>(https?:\/\/.*\.(?:png|jpg))<\/a>/gi,'<img src="$1">');
console.log(message);
//expect: <img src="http://example.com/example.jpg">

work on regex101

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
3142 maple
  • 865
  • 2
  • 11
  • 27

3 Answers3

3

Replace doesn't change the string it's called on, but return a new string. Just change to:

var message='<a href="http://example.com/example.jpg" target="_blank" rel="noopener noreferrer">http://example.com/example.jpg</a>';
message = message.replace(/<a.*>(https?:\/\/.*?\.(?:png|jpg))<\/a>/gi,'<img src="$1">');
console.log(message);
//expect: <img src="http://example.com/example.jpg">
Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
1

replace doesn't replace the original string, it return a new string that is the result of the replacemet, you have to store that new string in a variable and log it like this:

var message='<a href="http://example.com/example.jpg" target="_blank" rel="noopener noreferrer">http://example.com/example.jpg</a>';


var result = message.replace(/<a.*>(https?:\/\/.*\.(?:png|jpg))<\/a>/gi,'<img src="$1">');
console.log(result);
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
1
  var message='<a href="http://example.com/example.jpg" target="_blank"     
  rel="noopener noreferrer">http://example.com/example.jpg</a>';
  var newString=message.replace(/<a.*>(https?:\/\/.*\.(?:png|jpg))<\/a>/gi,'<img src=$1">');
  alert(newString);

You need to consume the new string, replace wont rewrite.

Midhun Mohan
  • 649
  • 1
  • 5
  • 13