How to remove trailing slash from URL?


Hi, How can I remove the ending slash from a URL using Javascript?

Answer ( 1 )


    You can remove the trailing slash from a URL by using the “replace” method on the URL.

    const url = '';
    const newUrl = url.replace(//$/, '');
    console.log(newUrl); // Outputs: ''

    In this example, the replace method is called on the url string, passing a regular expression “//$/” as the first argument. This regular expression matches a forward slash (/) at the end of the string ($). The second argument, an empty string, replaces the match with nothing, effectively removing the trailing slash.

    The result of the replace method is assigned to the newUrl variable, which now holds the URL without the trailing slash.

Leave an answer