tags:

views:

43

answers:

2

string could be anything @username is the link in multi-line string.. we need to link the @username anywhere in the url.. just like twitter

     $text = preg_replace('!(^|\W)@(([a-z0-9]+(\.?[-_a-z0-9]+)*)+)!', '\\1<a href="http://$2.'.site::$domain_only.'"&gt;@$2&lt;/a&gt;', $text);

its my php version.. how can i convert it or use it same with javascript.

+1  A: 

You can convert the code nearly one-on-one:

text = text.replace(/@+([a-z0-9]+(\.?[-_a-z0-9]+)*){2,255}/g, "<a href='http://$0.".site::$domain_only."'/&gt;$0&lt;/a&gt;");
text = text.replace("='http://@", "='http://");

And you will need to replace site::$domain_only with its value, e.g.:

var domain_only = '…';
text = text.replace(/@+([a-z0-9]+(\.?[-_a-z0-9]+)*){2,255}/g, "<a href='http://$0."+domain_only+"'/&gt;$0&lt;/a&gt;");
text = text.replace("='http://@", "='http://");

But I would rather use this regular expression:

/@+((?:[a-z0-9]+(?:\.?[-_a-z0-9]+)*){2,255})/g

Then you can use the match of the first group directly and don’t need to remove the @ afterwards:

var domain_only = '…';
text = text.replace(/@+((?:[a-z0-9]+(?:\.?[-_a-z0-9]+)*){2,255})/g, "<a href='http://$1."+domain_only+"'/&gt;$1&lt;/a&gt;");
Gumbo
$text = preg_replace('!(^|\W)@(([a-z0-9]+(\.?[-_a-z0-9]+)*)+)!', '\\1<a href="http://$2.'.site::$domain_only.'">@$2</a>', $text);how about this code?
Basit
A: 

Also you can add desired methods to JavaScript String object, like

String.prototype.linkuser=function(){
    return this.replace(/[@]+[A-Za-z0-9-_]+/g,function(u){
        return u.link('http://'+u.slice(1).toLowerCase()+'.example.com/');
    });
};

And then just use it like

// var username = "RT @some0ne this isn't a @twitterUsername";
username.linkuser(); // RT <a href="http://some0ne.example.com/"&gt;@some0ne&lt;/a&gt; this isn't a <a href="http://twitterUsername.example.com/"&gt;@twitterUsername&lt;/a&gt;
Mushex Antaranian