これも機能します:
url = url.replace(/\/$|$/, '/');
例:
let urlWithoutSlash = 'https://www.example.com/path';
urlWithoutSlash = urlWithoutSlash.replace(/\/$|$/, '/');
console.log(urlWithoutSlash);
let urlWithSlash = 'https://www.example.com/path/';
urlWithSlash = urlWithoutSlash.replace(/\/$|$/, '/');
console.log(urlWithSlash);
出力:
https://www.example.com/path/
https://www.example.com/path/
末尾のスラッシュまたは末尾のスラッシュがないものを末尾のスラッシュに置き換えます。したがって、スラッシュが存在する場合は、スラッシュが1つに置き換えられます(基本的にはそのままにしておきます)。存在しない場合は、末尾にスラッシュが追加されます。