0

I saw the other posts but none of them help me ...

So, i tried to match url in a string in javascript with regex it works perfectly on regex101 but fails in javascript.

var matches = feed.content.match(
    '/((http|https|ftp):\/\/([a-zA-Z0-9\.\-\_\%]+\/?){1}([a-zA-Z0-9\.\-\_]+\/?)*(\?[a-zA-Z0-9\.\-\_\%\+\=\&\:]*)*)/ig'
    );

And firebug returns me

SyntaxError: invalid quantifier

Please can you help me ?

3
  • 4
    Regexes should not have quotes around them. Commented Aug 1, 2014 at 13:34
  • You're also escaping way more characters than you need to, making it difficult to read. Commented Aug 1, 2014 at 13:35
  • Perhaps use a regexp object and make this easier on yourself as well. var re = new RegExp('((https?|ftp)://([\\w%.-]+/?)([\\w.-]+/?)*(\\?[\\w%.+=&:-]*)*)', 'gi') Commented Aug 1, 2014 at 13:48

2 Answers 2

1

As pointed out in the comments, you should remove the single quotes enclosing the regex. As well as that, I would propose making a few changes to the expression itself:

((https?|ftp):\/\/([\w.%-]+\/?)([\w.-]+\/?)*(\?[\w.%+=&:-]*)*)

The ? after the smeans that it is optional, so http and https will both match. \w is the word character class, so that covers A-Za-z0-9_ much more concisely. There's no need to escape all the symbols but a useful trick is to put the - at the end of the character class, so that it isn't interpreted as a range between two characters. The {1} isn't necessary as that's the default behaviour.

updated on regex101

Sign up to request clarification or add additional context in comments.

Comments

0

You're passing the regex as a string - just get rid of the outer quotes.

var matches = feed.content.match(
    /((http|https|ftp):\/\/([a-zA-Z0-9\.\-\_\%]+\/?){1}([a-zA-Z0-9\.\-\_]+\/?)*(\?[a-zA-Z0-9\.\-\_\%\+\=\&\:]*)*)/ig
    );

Comments

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.