I have a text and a script
JavaScript
x
9
1
var x = "This is an example url http://www.longurl.com/?a=example@gmail.com&x=y1 and this must me a example url";
2
3
function getMatch(str) {
4
var urlRegex = '(?!mailto:)(?:(?:http|https|ftp)://)(?:\S+(?::\S*)?@)?(?:(?:(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[0-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,})))|localhost)(?::\d{2,5})?(?:(/|\?|#)[^\s]*)?';
5
var reg = new RegExp(urlRegex, 'ig');
6
return str.match(reg);
7
}
8
9
console.log(getMatch(x));
The expected outcome must be
JavaScript
1
2
1
[ http://www.longurl.com/?a=example@gmail.com&x=y1 ]
2
but the below getMatch is giving me incorrectly (skipping &x=y1)
JavaScript
1
2
1
http://www.longurl.com/?a=example@gmail.com
2
How do I modify the function to return a complete URL
NOTE: This happens only when the email arguments are passed after it finds @ character, the function behaves weird.
Advertisement
Answer
Why not simplify:
JavaScript
1
12
12
1
var x = `This is an example url http://www.longurl.com/?a=example@gmail.com&x=y1 and this must me a example url
2
3
http:// www.longurl.com/?a=example@gmail.com&x=y1 (with an arbitrary number of spaces between the protocol and the beginning of the url)
4
here is a mailto:a@b.c?subject=aaa%20bbb and some more text
5
So https://www.google.com/search?q=bla or ftp://aaa:bbb@server.com could appear`
6
7
function getMatch(str) {
8
var urlRegex = /((mailto:|ftp://|https?://)S+?)[^s]+/ig;
9
return str.match(urlRegex);
10
}
11
12
console.log(getMatch(x));