我必须用 JS 重写这段代码:
$formateTweet = preg_replace("/http([^ ]*)/", "<a target=\"_blank\" href=\"http\\1\">http\\1</a>", $formateTweet);
$formateTweet = preg_replace("/@([^ ]*)/", "<a target=\"_blank\" href=\"http://twitter.com/\\1\">@\\1</a>", $formateTweet);
$formateTweet = preg_replace("/#([^ ]*)/", "<a target=\"_blank\" href=\"http://twitter.com/search?q=%23\\1\">#\\1</a>", $formateTweet);
我写道:
formattedTweet = formattedTweet.replace(/http([^ ]*)/, "<a target=\"_blank\" href=\"http\\1\">http\\1</a>");
formattedTweet = formattedTweet.replace(/@([^ ]*)/, "<a target=\"_blank\" href=\"http://twitter.com/\\1\">@\\1</a>");
formattedTweet = formattedTweet.replace(/#([^ ]*)/, "<a target=\"_blank\" href=\"http://twitter.com/search?q=%23\\1\">#\\1</a>");
但没有成功。例如,对于推文“@test bla bla”,我得到
<a target="_blank" href="http://twitter.com/\1">@\1</a> bla bla
虽然我应该得到
<a target="_blank" href="http://twitter.com/test">@test</a> bla bla
我想我必须更改正则表达式,但是我应该写什么呢?我认为问题来自于“1”没有从匹配器中获取值
最佳答案
不确定这是否是您想要的,但这应该是上面 PHP 代码的重写:
formattedTweet = formattedTweet.replace(/http([^ ]*)/g, "<a target=\"_blank\" href=\"http$1\">http$1</a>");
formattedTweet = formattedTweet.replace(/@([^ ]*)/g, "<a target=\"_blank\" href=\"http://twitter.com/$1\">@$1</a>");
formattedTweet = formattedTweet.replace(/#([^ ]*)/g, "<a target=\"_blank\" href=\"http://twitter.com/search?q=$1\">#$1</a>");
我所做的是:
- 添加
g
修饰符以替换多次出现的情况。 - 为正则表达式中的捕获组添加了
$1
占位符。
关于javascript - PHP 中的反向引用到 JS 正则表达式翻译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23783944/