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
  • 28,235
  • 15
  • 95
  • 135
3142 maple
  • 787
  • 1
  • 8
  • 26

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
  • 28,235
  • 15
  • 95
  • 135
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
  • 29,774
  • 5
  • 43
  • 68
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
  • 531
  • 1
  • 4
  • 11