简体   繁体   中英

Javascript Regex url replace

I am trying to use a regex to replace image,video and other urls that come overs as messages. I thought everything was working but I am running into a problem with the last case of replacing urls like www.google.com. It is now adding localhost:3000 to the front of those url. I am not the best with regex but it looks like the regex is working in the HTML as the href is www.google.com. Can anyone help see where this is going wrong?

var image_url = /([a-z\-_0-9\/\:\.]*\.(jpg|jpeg|png|gif))/i;
var message = text.replace(image_url,'<a href="$1" target="_blank"><img    width=100px height=100px src="$1"/></a>')
var video_url = /([a-z\-_0-9\/\:\.]*\.(mp4|webm|ogg))/i;
message = message.replace(video_url,'<a href="$1" target="_blank"><video src="$1"></video></a>')
var exp_url = /(?:^|[^"'])(https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})/gi;
message = message.replace(exp_url,'<a href="$1" target="_blank">$1</a>')

Was able to figure it out. I wasn't adding http:// if it wasn't there.

var image_url = /([a-z\-_0-9\/\:\.]*\.(jpg|jpeg|png|gif))/i;
var message = text.replace(image_url,'<a href="$1" target="_blank"><img width=100px height=100px src="$1"/></a>')
var video_url = /([a-z\-_0-9\/\:\.]*\.(mp4|webm|ogg))/i;
message = message.replace(video_url,'<a href="$1" target="_blank"><video src="$1"></video></a>')
var http_reg = /(?:^|[^"'])(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
message = message.replace(http_reg, '<a href="$1" target="_blank">$1</a>');
var www_reg = /(?:^|[^"'])(^|[^\/])(www\.[\S]+(\b|$))/gim;
message = message.replace(www_reg, '$1<a href="http://$2" target="_blank">$2</a>');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM