Add leading and trailing slashes to string if needed using regex

javascript, regex

Solution

[With thanks to Dmitry!]

This will work for your first 5 cases:

string.replace(/^\/?([^\/]+(?:\/[^\/]+)*)\/?$/, '/$1/');

You're then left with the null string, which you can handle using the OR operator (`||`):

string.replace(/^\/?([^\/]+(?:\/[^\/]+)*)\/?$/, '/$1/') || '/';

Snippet:

var RE = /^\/?([^\/]+(?:\/[^\/]+)*)\/?$/;

console.log('/path'.replace(RE, '/$1/') || '/');
console.log('path/'.replace(RE, '/$1/') || '/');
console.log('path'.replace(RE, '/$1/') || '/');
console.log('/path/'.replace(RE, '/$1/') || '/');
console.log('/'.replace(RE, '/$1/') || '/');
console.log(''.replace(RE, '/$1/') || '/');
console.log('path/with/embedded/slashes'.replace(RE, '/$1/') || '/');

Problem

I'm having an issue, where I need to add leading and trailing slashes to string if it's not having them, or do nothing if string is already has it. For example: ``` "/path" => "/path/" "path/" => "/path/" "path" => "/path/" "/path/" => "/path/" "/" => "/" "" => "/" ``` I've tried to use this regular expression, but it's not adding trailing slash: ``` '/path'.replace(/(^\/?)|(\/?$)/, '/'); // output is "/path" ```

Original source