2015-09-04 21 views
1

對於一個小小的web應用,我使用JS將字符串內的url更改爲可點擊的url,同時將url更改爲「點按此處」。但問題是如果我保持URl一樣,而不改變它'點擊這裏',它一切正常。但是,如果我改變它,可點擊的鏈接指向一個錯誤頁面:將字符串中的URL更改爲可單擊的鏈接,同時更改其值

Not Found

The requested URL /client/http://www.google.com' target='_blank'>tap here was not found on this server.

下面是我使用的作品的代碼(不更改爲「輕觸這裏」)

$('.discussion').ready(function(){ 

    $('.discussion #messages p').each(function(){ 

     var str = $(this).html(); 

     var regex = /(https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?)/ig 

     var replaced_text = str.replace(regex, "<a href='$1' target='_blank'>$1</a>"); 

     $(this).html(replaced_text); 


    }); 
}); 

這是一個我想工作,但提供了錯誤:

$('.discussion').ready(function(){ 

    $('.discussion #messages p').each(function(){ 

     var str = $(this).html(); 

     var regex = /(https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?)/ig 

     var replaced_text = str.replace(regex, "<a href='$1' target='_blank'>tap here</a>"); 

     $(this).html(replaced_text); 


    }); 
}); 

[編輯],這裏的HTML

<ol class="discussion" scroll-bottom="replies"> 
    <div ng-class="getClass($index)" ng-repeat="reply in replies track by $index"> 
     <li ng-repeat="item in reply.text.replace('?','.').replace('!','.').split('. ') track by $index" class="fix-clutter"> 
     <div class="avatar"> 
      <img ng-src="{{reply.avatar}}"> 
     </div> 

     <div id="messages" class="animated slideInUp"> 

      <p class="animated fadeInUp">{{item}}</p> 

     </div> 
     </li> 
    </div> 
    </ol> 

回答

0

我複製並粘貼在這裏你的代碼:用以下HTML http://plnkr.co/edit/CK2vJdeIxtN1Bvt7Kce5?p=preview

<div class="discussion"> 
    <div id="messages"> 
    <p> 
     http://stackoverflow.com/questions/32395188/changing 
    </p> 
    <p> 
     http://stackoverflow.com/questions/32395188/changing 
    </p> 
    </div> 
</div> 

一切都工作得很好,在這種特定情況下。你能粘貼你的HTML嗎? 然而,正則表達式並不正確。如果在URI上添加「破折號」,則正則表達式無法獲得完整的URI,並且破折號。

更新: 我再次檢查...和問題是由正則表達式規則造成的90%。

哪裏是打破另一種情況是,當你已經在你的HTML與「href標記」爲下面的代碼的鏈接:您的時間

<div class="discussion"> 
    <div id="messages"> 
    <p> 
     <a href="http://stackoverflow.com/questions/32395188/changing'>LINK</a> 
    </p> 
    </div> 
</div> 
+0

TNX,我已經添加了HTML。我在HTML中沒有任何鏈接,數據通過php添加。 – jiblylabs

+0

不幸的是這並不能幫助我很多。我需要來自php的示例數據來修復正則表達式規則。順便說一句,我不知道你在使用Angular。在這一點上,我建議你將所有這些邏輯移動到AngularJS中的自定義過濾器,並將其應用於** item **,如:{{item | myCustomFilter}}。 (https://docs.angularjs.org/api/ng/filter/filter) – Daniele