Basit
Basit

Reputation: 17184

regex php to javascript

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.'">@$2</a>', $text);

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

Upvotes: 0

Views: 77

Answers (2)

Mushegh A.
Mushegh A.

Reputation: 1431

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/">@some0ne</a> this isn't a <a href="http://twitterUsername.example.com/">@twitterUsername</a>

Upvotes: 0

Gumbo
Gumbo

Reputation: 655209

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."'/>$0</a>");
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+"'/>$0</a>");
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+"'/>$1</a>");

Upvotes: 1

Related Questions