开发者

REGEX Str Replace- finding link text and making them links

开发者 https://www.devze.com 2023-04-08 00:10 出处:网络
I\'ve written this functionality in Flash before without issue; however, I\'m now attempting to do it with JavaScript and I\'m running into some difficulty.

I've written this functionality in Flash before without issue; however, I'm now attempting to do it with JavaScript and I'm running into some difficulty.

Using Regex, I'm trying to scour a string looking for anything that resembles a link... for example http://www.google.com or http://stacoverflow.com/question/ask; then wrap that result with the appropriate: :

<script type="text/javascript>
var mystring = "I'm trying to make this link http://facebook.com/lenfontes active." 
/// REGEX that worked in Flash to grab ALL parts of the URL including after the .com...

var http = /\b(([\w-]+:\/\/?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|\/)))/gi;

// preform the replace based on the Regex
mystring = mystring.replace(http, function(){   
    var link = arguments[0];
if (link.indexOf("http") == -1){
    link = "http://" + link;}
    return "<a href='"+link+"'>"+arguments[0]+"</a>";
});

$('#results).html(mystring);
</script>

The issue I'm having: anything after the ...com/ is ignored. Therefore the link isn't correct...

Even while I post this question, the Stack Overflow interface has taken my text and rendered it out with the appropriate link tags... I need to do that.

Any suggestion开发者_高级运维s welcomed.

-- Update:

Sorry, let me expand.. I'm not only looking for http:// it needs to detect and wrap links that start with "https://" and/or just start with "www"


Your regex doesn't work because ECMA (JavaScript) doesn't support POSIX character classes, so [:punct:] ignores the . in .com.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号