alex alex - 6 months ago 34
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?


Sample string:


Try that:

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

Run the sample here