返回PHP中的引用到JS正则表达式转换

时间:2014-05-21 13:01:08

标签: 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>");

但没有成功。比如推特&#34; @test bla bla&#34;我得到

<a target="_blank" href="http://twitter.com/\1">@\1</a> bla bla

虽然我应该

<a target="_blank" href="http://twitter.com/test">@test</a> bla bla

我想我必须改变正则表达式,但我应该写什么呢?我认为这个问题来自&#34; 1&#34;没有从匹配器中获取值

2 个答案:

答案 0 :(得分:2)

对于javascript中的backreferrencing,请使用$1而不是\\1

formattedTweet = "@test bla bla";
formattedTweet = formattedTweet.replace(/@([^ ]*)/, "<a target=\"_blank\" href=\"http://twitter.com/$1\">@$1</a>");
console.log(formattedTweet);

输出

<a target="_blank" href="http://twitter.com/test">@test</a> bla bla 

答案 1 :(得分:2)

不确定这是不是你想要的,但这应该是上面重写的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. 在regexp中为捕获组添加了$1占位符。
相关问题