JS:在文本查找网址,让您链接 [英] JS: Find URLs in Text, Make Links
本文介绍了JS:在文本查找网址,让您链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么是在JS改写下面的PHP code是,这样的文本斑点内部的URL链接可能与HTML链接被取代?我已经开始了一个的jsfiddle 。
< PHP//王家军前pression过滤器
$ reg_exUrl =/(HTTP | HTTPS | FTP | FTPS)\\:\\ / \\ / [A-ZA-Z0-9 \\ - \\] + \\ [A-ZA-Z] {2,3}(\\ / \\ S *)/?;//文本要过滤的网址为
$文字=要过滤文本放在这里http://google.com。//检查是否有在文本中的网址
如果(preg_match($ reg_exUrl,$文字$网址)){ //作出的URL超链接
回声preg_replace($ reg_exUrl,< A HREF ={$网址[0]}> {$网址[0]}< / A>中,$文字);}其他{ //如果文本没有网址,只是返回文本
回声$文本;}
?>
解决方案
使用这样的:
VAR文本=要过滤文本放在这里http://google.com。
文字= text.replace(
/((http|https|ftp|ftps)\\:\\/\\/[a-zA-Z0-9\\-\\.]+\\.[a-zA-Z]{2,3}(\\/\\S *)?)/G,
'&所述; A HREF =$ 1> $ 1所述; / A>'
);
说明:
的先按g
这里是一个全球性的标志;它将替换所有的URL。
我还添加了一个捕获组为整个前pression,所以我可以使用反向引用 $ 1
。
What would be the following PHP code rewritten in JS be, so that url links inside of text blobs could be replaced with html links? I've started a jsfiddle.
<?php
// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// The Text you want to filter for urls
$text = "The text you want to filter goes here. http://google.com";
// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {
// make the urls hyper links
echo preg_replace($reg_exUrl, "<a href="{$url[0]}">{$url[0]}</a> ", $text);
} else {
// if no urls in the text just return the text
echo $text;
}
?>
解决方案
Use this:
var text = "The text you want to filter goes here. http://google.com";
text = text.replace(
/((http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?)/g,
'<a href="$1">$1</a>'
);
Explanation:
The g
here is a global flag; it will replace all urls.
I also added an capture group for the entire expression, so I could use the backreference $1
.
这篇关于JS:在文本查找网址,让您链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文