const regex = /(?:(?:http|https):\/\/)?(?:www.)?(?:instagram.com|instagr.am|instagr.com)\/(\w+)/igm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(?:(?:http|https):\\\/\\\/)?(?:www.)?(?:instagram.com|instagr.am|instagr.com)\\\/(\\w+)', 'igm')
const str = `http://instagram.com/username
http://instagram.com/username?modal=true
https://instagram.com/username
https://instagram.com/username?modal=true
http://www.instagram.com/username
http://www.instagram.com/username?modal=true
https://www.instagram.com/username
https://www.instagram.com/username?modal=true
instagram.com/username
instagram.com/username?modal=true
www.instagram.com/username
www.instagram.com/username?modal=true
http://instagr.am/username
http://instagr.am/username?modal=true
http://www.instagr.am/username
http://www.instagr.am/username?modal=true
https://instagr.am/username
https://instagr.com/username
https://instagr.am/username?modal=true
https://www.instagr.am/username
https://www.instagr.am/username?modal=true`;
// 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