[英]extract url from string with Javascript
this sounds like something you could just google, but been looking for hours. 这听起来像你可以谷歌,但一直在寻找几个小时。
basically have this string i am ajaxing from another site 基本上有这个字符串我从另一个网站ajaxing
'function onclick(event) { toFacebook("http://www.domain.com.au/deal/url-test?2049361208?226781981"); }'
it comes out like that because im extracting the onclick. 它就像那样,因为即时提取onclick。
i just want to extract the url from the string. 我只是想从字符串中提取url。
any help would be greatly appreciated. 任何帮助将不胜感激。
---- edit ---- ----编辑----
OK IF I GO HERE..http://regexlib.com/RESilverlight.aspx regext online tester 好的,如果我去这里..http://regexlib.com/RESilverlight.aspx regext在线测试
and run this regex. 并运行此正则表达式。
(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?
on my string, it highlights the url perfectly.. i just can get it to run with JS? 在我的字符串上,它完美地突出显示了网址..我只是可以让它与JS一起运行?
if it is always with the dash (i'm assuming you want everything before the dash), you can use the split method: 如果它总是使用破折号(我假设你想要破折号之前的所有东西),你可以使用分割方法:
var arr = split(val);
your data will be in arr[0] 你的数据将在arr [0]
you can use these functions in javascript: 你可以在javascript中使用这些函数:
function parseUrl1(data) {
var e=/^((http|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+\.[^#?\s]+)(#[\w\-]+)?$/;
if (data.match(e)) {
return {url: RegExp['$&'],
protocol: RegExp.$2,
host:RegExp.$3,
path:RegExp.$4,
file:RegExp.$6,
hash:RegExp.$7};
}
else {
return {url:"", protocol:"",host:"",path:"",file:"",hash:""};
}
}
function parseUrl2(data) {
var e=/((http|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+\.[^#?\s]+)(#[\w\-]+)?/;
if (data.match(e)) {
return {url: RegExp['$&'],
protocol: RegExp.$2,
host:RegExp.$3,
path:RegExp.$4,
file:RegExp.$6,
hash:RegExp.$7};
}
else {
return {url:"", protocol:"",host:"",path:"",file:"",hash:""};
}
}
References :http://lawrence.ecorp.net/inet/samples/regexp-parse.php 参考文献:http://lawrence.ecorp.net/inet/samples/regexp-parse.php
just ended up doing this 刚结束这样做
$a.substring($a.indexOf("http:"), $a.indexOf("?"))
regular expressions are beyond me. 正则表达式超出我的范围。
var urlRegex = /(http?:\/\/[^\s]+)/g;
var testUrl = text.match(urlRegex);
if (testUrl === null) {
return "";
}else {
var urlImg = testUrl[0];
return urlImg;
}
yourFunction.toString().split("'")[1]
完成这项工作。
Edit: Here is another solution that will extract the url: 编辑:这是另一个解压缩网址的解决方案:
var function = 'function onclick(event) { toFacebook("http://www.domain.com.au/deal/url-test?2049361208?226781981"); }'
function.match(/(http:[^"]+)/)[0]
Old answer: Use Regular Expressions: 旧答案:使用正则表达式:
javascript regex to extract anchor text and URL from anchor tags javascript正则表达式从锚标记中提取锚文本和URL
var url_match = /https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?/;
alert(url_match.test("http://stackoverflow.com"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.