alex alex - 21 days ago 9
Javascript Question

How to properly separate this regex into two lines?

I have a regex that checks if a string is an URL:

const regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/


I tried this:

const regex = '/(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?' + // eslint-disable-line
'(\/|\/([\w#!:.?+=&%!\-\/]))?/' // eslint-disable-line


But the regex doesn't match anymore. Same for this one:

const regex = new RegExp(['/(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?', // eslint-disable-line
'(\/|\/([\w#!:.?+=&%!\-\/]))?/'].join('')) // eslint-disable-line


What's the proper way of doing this?

EDIT:

Sample string:
http://vrcam-10065475.image.myqcloud.com/7a88620cb5ec7eb90164.jpg?imageView2/2/w/600/h/600/q/100/format/jpg

Answer

Try that:

var regex = RegExp(
  "(http|https)://(\\w+:{0,1}\\w*)?(\\S+)(:[0-9]+)?" +
  "(/|/([\\w#!:.?+=&%!-/]))?"
);

Run the sample here