0

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.

2 Answers 2

1

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>");
Sign up to request clarification or add additional context in comments.

1 Comment

$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?
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.