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,426
  • 12
  • 60
  • 102

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
  • 85,475
  • 27
  • 147
  • 152
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,482
  • 22
  • 32
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
  • 4,662
  • 6
  • 38
  • 66