2

How to get rid of the comma (,) in the output? Is there any better way to search for the url from the string or sentance.

alert("   http://www.cnn.com  df".match(/https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?/));

Output from alert is:

http://www.cnn.com,,,,
user1595858
  • 3,700
  • 15
  • 66
  • 109

3 Answers3

1

That happens because alert will convert the result of match, which is an array, to a string. To get the relevant part of the array use the following:

alert("   http://www.cnn.com  df".match(/https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?/)[0]);
João Silva
  • 89,303
  • 29
  • 152
  • 158
0

You (*) in your regex makes return value an array with multiple matching results. You can do using ?:

alert("   http://www.cnn.com  df".match(/https?:\/\/(?:[-\w\.]+)+(?::\d+)?(?:\/(?:[\w/_\.]*(?:\?\S+)?)?)?/));

or get first value of a returned array:

alert("   http://www.cnn.com  df".match(/https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?/)[0]);
mask8
  • 3,560
  • 25
  • 34
0

add a g modifire at the end of your regEx.

 alert(
"http://www.cnn.com df".match(/https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?/g)
);
Dariush Jafari
  • 5,223
  • 7
  • 42
  • 71