Joshua Bitton
Joshua Bitton

Reputation: 403

Regex with strings contaning url and text

I'm trying to replace a string containing a url and text to just the url. I'm doing this:

const url = 'hello https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test'
  
const urlreg = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/g;

url.replace(urlreg,(url)=> {
    return url
  })

When doing this it will return the text, anyway to remove the text?

Upvotes: 0

Views: 28

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370789

While it would be possible to match and remove the text, it'd make more sense to match and construct a new string from just the URLs - not with .replace, but with .match:

const url = 'hello https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test';
const urlreg = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/g;
const stringWithOnlyURLS = url.match(urlreg).join(' ');
console.log(stringWithOnlyURLS);

If there might not be any URLs, then alternate with the empty array to avoid problems with null results:

const stringWithOnlyURLS = (url.match(urlreg) || []).join(' ');

Upvotes: 1

Related Questions