我试图找到一个sting的URL。我想检查字符串是否包含任何URL。
为此我写了代码:
function get_url_from_string(str) {
var searchText = str,
urls = searchText.match(/\b(http|https)?(:\/\/)?(\S*)\.(\w{2,4})\b/ig);
for (var i = 0, il = urls.length; i < il; i++) {
var ur=urls[i];
}
return ur;
}
但它只返回带有任何参数的URL。例如,如果我通过:
我想获得完整的网址。 我不知道正则表达式。 请帮忙。 谢谢
答案 0 :(得分:2)
试试这个 -
/\b(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?\s/
答案 1 :(得分:2)
试试这个对我来说效果很好。
var url_regex = /(?:(?:https?|ftp):\/\/)?(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?/gi;
var text = "some text string here!!";
var urls_array = [];
while ((urls = url_regex.exec(text)) !== null) {
urls_array.push(urls[0]);
}
此代码用于我的项目
答案 2 :(得分:2)
function get_url_from_string(str) {
var searchText = str,
urls = searchText.match(/\b(http|https)?(:\/\/)?(\S*)\.(\w{2,4})?(.*)\b/ig);
for (var i = 0, il = urls.length; i < il; i++) {
var ur=urls[i];
}
alert(ur);
return ur;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="x" onclick="get_url_from_string('https://www.youtube.com/watch?v=eHOc-4D7MjY')">click here
</button>