- Instant help with your JavaScript coding problems

Remove protocol from URL with JavaScript

Question:
How to remove protocol from URL with JavaScript?
Answer:
const removeProtocol = (url) => {
    if (!url) {
        return '';
    }

    return url.replace(/(^\w+:|^)\/\//, '');
}
Description:

To remove the protocol like http:// , https:// , ftp:// , //  from an URL string with JavaScript simply use the replace method with a small regular expression.

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced.

 

Share "How to remove protocol from URL with JavaScript?"
Related snippets:
Tags:
remove, delete, protocol, http, https, ftp, url, javascript
Technical term:
Remove protocol from URL with JavaScript