开发者

extract url from string with Javascript

开发者 https://www.devze.com 2023-01-22 23:40 出处:网络
this sounds like something you could just google, but been looking for hours. basically have this string i am ajaxing from another site

this sounds like something you could just google, but been looking for hours.

basically have this string i am ajaxing from another site

'function onclick(event) { toFacebook("http://www.domain.com.au/deal/url-test?2049361208?226781981"); }'

it comes out like that because im extracting the onclick.

i just want to extract the url from the string.

any help would be greatly appreciated.

---- edit ----

OK IF I GO HERE..http://regexlib.com/RESilverlight.aspx regext onlin开发者_C百科e tester

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?


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]


you can use these functions in 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


just ended up doing this

$a.substring($a.indexOf("http:"), $a.indexOf("?"))

regular expressions are beyond me.


yourFunction.toString().split("'")[1] does the job.


 var urlRegex = /(http?:\/\/[^\s]+)/g;

    var testUrl = text.match(urlRegex);

    if (testUrl === null) {

    return "";

      }else {

    var urlImg = testUrl[0];

    return urlImg;

     }


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

var url_match = /https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?/;

alert(url_match.test("http://stackoverflow.com"));
0

精彩评论

暂无评论...
验证码 换一张
取 消