正则表达式php到javascript
字符串可以是任何内容@username是多行字符串中的链接。。我们需要将@username链接到url中的任意位置。。就像推特一样正则表达式php到javascript,php,javascript,Php,Javascript,字符串可以是任何内容@username是多行字符串中的链接。。我们需要将@username链接到url中的任意位置。。就像推特一样 $text = preg_replace('!(^|\W)@(([a-z0-9]+(\.?[-_a-z0-9]+)*)+)!', '\\1<a href="http://$2.'.site::$domain_only.'">@$2</a>', $text); $text=preg\u replace('!(^\W)@(([a
$text = preg_replace('!(^|\W)@(([a-z0-9]+(\.?[-_a-z0-9]+)*)+)!', '\\1<a href="http://$2.'.site::$domain_only.'">@$2</a>', $text);
$text=preg\u replace('!(^\W)@(([a-z0-9]+(\.?[-\U a-z0-9]+)*)+)!'、'\\1',$text);
这是我的php版本。。如何将其转换或与javascript一起使用。您可以几乎一对一地转换代码:
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://");
但我宁愿使用这个正则表达式:
/@+((?:[a-z0-9]+(?:\.?[-_a-z0-9]+)*){2,255})/g
然后,您可以直接使用第一组的匹配项,而无需在之后删除@
:
var domain_only = '…';
text = text.replace(/@+((?:[a-z0-9]+(?:\.?[-_a-z0-9]+)*){2,255})/g, "<a href='http://$1."+domain_only+"'/>$1</a>");
var-domain_only='…';
text=text.替换(/@+((?:[a-z0-9]+(?:\.?[-\U a-z0-9]+)*){2255})/g,“”;
您还可以向JavaScript字符串对象添加所需的方法,如
String.prototype.linkuser=function(){
return this.replace(/[@]+[A-Za-z0-9-_]+/g,function(u){
return u.link('http://'+u.slice(1).toLowerCase()+'.example.com/');
});
};
然后像这样使用它
// 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>
//var username=“RT@some0ne这不是@twitter用户名”;
username.linkuser();//这不是一个好主意
$text=preg\u replace('!(^\W)@([a-z0-9]+(\.?[-\U a-z0-9]+)*)+)!'、'\\1',$text);这个代码怎么样?
// 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>