从字符串 javascript 中提取 URL

Extract URL from string javascript

本文关键字:提取 URL javascript 字符串      更新时间:2023-09-26

这是我只想从中提取URL的变量,例如在这种情况下,我希望最后的结果:http://url.com/index.php/foo/bar/new/key/34941cd947592adb1594b6f649468a33/

var variable = "function onclick(event) { setLocation('http://url.com/index.php/foo/bar/new/key/34941cd947592adb1594b6f649468a33/')}"

使用这个:

var testUrl = variable.match(/'(http:[^'s]+)'/),
    onlyUrl = testUrl && testUrl[1];

onlyUrl变量包含提取的 URL 或null

编辑:

之前只是对OP的回答。在更新以处理https之后:

var testUrl = variable.match(/'(https?:[^'s]+)'/),
    onlyUrl = testUrl && testUrl[1];