JSFiddle - React, Tailwind, and code Playground

JavaScript

const urls = [
    'https://www.twitter.com/mattkenefick',
    'http://www.twitter.com/mattkenefick',
    'www.twitter.com/mattkenefick',
    'twitter.com/mattkenefick',
    'https://www.instagram.com/tonightaliveofficial',
    'http://www.instagram.com/tonightaliveofficial',
    'www.instagram.com/tonightaliveofficial',
    'instagram.com/tonightaliveofficial',
    'vimeo.com/my-name-goes-here',
    'medium.com/@mattkenefick',
    'basic-name',
    '12345678',
    '',
];

/**
 * Parse username from social media URL
 *
 * @param string $url
 * @return string
 */
function parseUsername(url)
{
    let output = url;
    let matches;

    // Parse username
    matches = url.match(/(?:https?:\/\/)?(?:www.)?(?:twitter|medium|facebook|vimeo|instagram)(?:.com\/)?([@a-zA-Z0-9-_]+)/im);

    // Set output
    output = matches.length ? matches[1] : output;

    return output;
}


// Parse
for (const url of urls) {
    const name = parseUsername(url);

    console.log(`Extacted: [${name}] from ${url}`);
}

// Extacted: [mattkenefick] from https://www.twitter.com/mattkenefick
// Extacted: [mattkenefick] from http://www.twitter.com/mattkenefick
// Extacted: [mattkenefick] from www.twitter.com/mattkenefick
// Extacted: [mattkenefick] from twitter.com/mattkenefick
// Extacted: [tonightaliveofficial] from https://www.instagram.com/tonightaliveofficial
// Extacted: [tonightaliveofficial] from http://www.instagram.com/tonightaliveofficial
// Extacted: [tonightaliveofficial] from www.instagram.com/tonightaliveofficial
// Extacted: [tonightaliveofficial] from instagram.com/tonightaliveofficial
// Extacted: [my-name-goes-here] from vimeo.com/my-name-goes-here
// Extacted: [@mattkenefick] from medium.com/@mattkenefick
// Extacted: [basic-name] from basic-name
// Extacted: [12345678] from 12345678
// Extacted: [] from