alex alex - 1 year ago 74
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:

Answer Source

Try that:

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

Run the sample here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download