javascript - PHP 中的反向引用到 JS 正则表达式翻译

标签 javascript php regex

我必须用 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>");

我所做的是:

  1. 添加 g 修饰符以替换多次出现的情况。
  2. 为正则表达式中的捕获组添加了 $1 占位符。

关于javascript - PHP 中的反向引用到 JS 正则表达式翻译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23783944/

相关文章:

javascript - 描述 typescript .d.ts 文件的嵌套对象

c# - 如何以异步模式预加载 iframe 内容(一个 aspx 页面)以加快加载速度

javascript - 函数中未声明的 JavaScript 变量覆盖了使用

php - 如何为每个文本输入编写 $_POST 方法

php - 在后台运行繁重的 PHP 脚本

PHP PDO 查询问题作为对象返回 => "queryString"

php - 调试 zip 存档和下载

java - URI 参数中以逗号分隔 10 种货币的正则表达式模式

javascript - 带有元素标记名的错误正则表达式?

regex - 使用正则表达式从页面文本中提取数字