对于一个小 web 应用程序,我使用 JS 将字符串内的 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>
最佳答案
我将您的代码复制并粘贴到此处:http://plnkr.co/edit/CK2vJdeIxtN1Bvt7Kce5?p=preview使用以下 HTML:
<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>
关于javascript - 将字符串中的 URL 更改为可点击链接,同时更改其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32395188/