0

So I need to grab all urls in a string and return them in an array.

Here is what I have so far:

        var comment = 'Check out www.google.com and http://bing.com';
        var regexp = new RegExp('((ftp|http|https):\/\/)?(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?', 'gi');
        var urls = comment.match(regexp);

Right now its not returning anything, whereas I need it to return both urls. I have searched google and stack and lots of examples, but none are working for my needs.

All help is greatly appreciated.

Thanks!

Jim

1
  • You can always use Regexper to create a graph reprenseting your Regexp allowed patterns. Not an answer to your question, but a nice tool to help debug Regexp issues. Commented Mar 8, 2013 at 22:01

1 Answer 1

3

Your \ characters are being parsed as string escapes and aren't ending up in the regex.

Instead, you should use a regex literal:

/((ftp|http|https):\/\/)?(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi
Sign up to request clarification or add additional context in comments.

1 Comment

thank you so much. One last issue I am having, is using the sentence "Check out www.google.com and bing.com" it is capturing all of the words whereas I just need it to capture the urls. Ideas?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.