Match all urls from a string in vanilla JS


Matching all urls in a string using vanilla JavaScript

19 Mar, 2020 · 2 min read

Every needed to get all strings from a input. We wanted to migrate alot of landing pages from http to https and wanted to automate converting all sources.

I’ve build a node.js script, but the functions are really plain vanilla js. We first needed to index all urls to see if it was even possible to make them https, the script will return a array of urls for the given input.

The following script will find all url’s in the given input string and return a array of urls.

const input =
  '<a href="">Lorem</a> ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Risus ultricies tristique nulla aliquet enim. Sed viverra tellus in hac habitasse platea dictumst. <a href="">Ipsum</a> consequat nisl vel pretium lectus quam. Ultrices mi tempus imperdiet nulla malesuada pellentesque elit eget. Egestas congue quisque egestas diam in. Velit ut tortor pretium viverra suspendisse potenti. Donec ac odio tempor orci dapibus. Eget dolor morbi non arcu. In nisl nisi scelerisque eu. Commodo quis imperdiet massa tincidunt nunc pulvinar sapien. Mauris sit amet massa vitae tortor condimentum lacinia <a href="">quis</a> vel.';
const urls = input.match(/\b(https?:\/\/.*?\.[a-z]{2,4}\b)/g);
// Returns: ["", "", ""]

See the Pen Match all urls from a string by Chris Bongers (@rebelchris) on CodePen.

Let’s reach out and connect

I hope you like my blog initative, follow me on Facebook or Twitter to reach out or just be the first to know about any new blog articles.

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Removing all vowels with JavaScript

3 Dec, 2022 · 2 min read

Removing all vowels with JavaScript

10 games to learn JavaScript

2 Dec, 2022 · 3 min read

10 games to learn JavaScript

Join 2099 devs and subscribe to my newsletter