const regex = /(https?:\/\/)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&\/\/=]*)/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(https?:\\\/\\\/)?(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{2,256}\\.[a-z]{2,6}\\b([-a-zA-Z0-9@:%_\\+.~#?&\\\/\\\/=]*)', 'gm')
const str = `Welcome to RegExr 0.3b, an intuitive tool for learning, writing, and testing Regular Expressions. Key features include:
* real time results: shows results as you type
* code hinting: roll over your expression to see info on specific elements
* detailed results: roll over a match to see details & view group info below
* built in regex guide: double click entries to insert them into your expression
* online & desktop: regexr.com or download the desktop version for Mac, Windows, or Linux
* save your expressions: My Saved expressions are saved locally
* search Community expressions and add your own
* create Share Links to send your expressions to co-workers or link to them on Twitter or your blog [ex. http://RegExr.com?2rjl6]
Built by gskinner.com with Flex 3 [adobe.com/go/flex] and Spelling Plus Library for text highlighting [gskinner.com/products/spl].
https://google.com
https:google.com
www.cool.com.au
http://www.cool.com.au
http://www.cool.com.au/ersdfs
http://www.cool.com.au/ersdfs?dfd=dfgd@s=1
http://www.cool.com:81/index.html`;
// Reset `lastIndex` if this regex is defined globally
// regex.lastIndex = 0;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions