How to remove trailing slash from URL?

Asked by: alf93
Viewed: 259
Answers: 1
  • 0

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


Answer by: ChristianKovats

Answered on: 21 Jul 2023

  • 0

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.

Please log in to post an answer!