3

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"
1

2 Answers 2

7

[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/') || '/');

Sign up to request clarification or add additional context in comments.

6 Comments

Perhaps, the path is supposed to have optional slashes in the middle as well. In such cases (e.g. some/longer/path) the suggested solution would fail.
That's a good point. The OP will have to respond if that's the case.
Yet, your solution may be extended to ^\/?([^\/]+(?:\/[^\/]+)*)\/?$ to cover such cases.
@DmitryEgorov correct, it may have optional slashes in the middle. Right now, I've ended up with that solution: 'path'.replace(/^\/?([^\/]+)\/?$/, '/$1/');. It will return double slashes for an empty and single slash input string. That case could be resolved by simple condition. But it's a little hacky
@DmitryEgorov, that's brilliant. Now updated, but if you want to post it yourself for credit, I'll delete my answer.
|
0

Shorter:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.