0

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?

1 Answer 1

1

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(' ');
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the quick answer, would there be a way to therefore also take the text that isn't url?
Match URLs with the regular expression and replace with the empty string, and you'll get the text without any URLs

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.