如何使用JavaScript从一段文本中将URL提取到一个数组中 [英] How can i extract URL's from a piece of text into an Array using JavaScript

查看:170
本文介绍了如何使用JavaScript从一段文本中将URL提取到一个数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在HTML中有一个文本框,用户可以在其中输入任何类型的文本。它也可以包含URL。

I have a text box in HTML where user can enter any kind of text. It can include URL's as well.

如何使用JavaScript从该文本中将URL提取到数组中?

How can I extract URL's from that text into an array using JavaScript ?

此网址就如何替换文字。但我想将它们提取到一个数组中,以便我可以处理它们。

This URL gives a good example as to how to replace the text. But i would like to extract them into an array so i can process them.

var userText = "Hello, I can't http://google.com for c*ap" 
var urls = getUrlsFromText(userText); 
console.log("Urls!",urls) 
--> must give ['http://google.com']

编辑:不重复,因为我发现在我发布问题之前,正则表达式检测URL。我需要一种方法将匹配从字符串中提取到数组,

Not a duplicate as I found the Regex to detect URL's before i posted the question. i needed a way to extract the matches from the string to an Array,

推荐答案

只需使用 String.match()

function getUrlsFromText(input) {
    return input.match(/* your URL regex here */);
}

网址的正则表达式很容易找到,例如 https://mathiasbynens.be/demo/url-regex

A regex for URLs is easy to find, e.g. https://mathiasbynens.be/demo/url-regex.

这篇关于如何使用JavaScript从一段文本中将URL提取到一个数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆