ConorJohn ConorJohn - 5 months ago 13
Javascript Question

Regular expression requirements not strict enough

Using regex I am attampting to limit the user's input to one of the following scenarios:


  • http(s)://www.instagram.com/user

  • www.instagram.com/user

  • http(s)://instagram.com/user

  • instagram.com/user



However, once that final case is satisfied it will accept any random string before the "instagram.com", this isn't imperitive but it's more for my own peace of mind. The regular expression I am using is the following:

control.value.match(/(?:(?:http|https):\/\/)?(?:www.)?instagram.com\/([A-Za-z0-9-_]+)/igm)


I would like to have it so that only one of the above cases validate. Thanks in advance for the help.

Answer

If you want to ensure that the entire content matches a regular expression, there are a few ways, but my favorite is just using the regular expression itself.

You can use the line start ^ and line end $ characters. These are called anchors and you can read about them at http://www.regular-expressions.info/anchors.html

Your code would look like this:

control.value.match(/^(?:(?:http|https):\/\/)?(?:www.)?instagram.com\/([A-Za-z0-9-_]+)$/igm)

This only works because you're looking at a single line of text. Your m flag would imply multiline text (which doesn't make any sense with a url), so you should take a closer look at http://www.regular-expressions.info/modifiers.html. In javascript, modifiers for the entire expression are placed as flags at the end. You can see examples of that at http://www.rexegg.com/regex-modifiers.html.

In your example, your flags are igm and come after the closing /.

Comments