I
I
indeveloping2022-02-19 17:42:57
Regular Expressions
indeveloping, 2022-02-19 17:42:57

How to add a slash to the end of a line in a regular expression?

There is a regular expression that removes duplicate slashes from the path:

const url = 'http://localhost////example///author/admin';
clean_url = url.replace(/([^:]\/)\/+/g, "$1")
console.log(clean_url) // http://localhost/example/author/admin



How to complete it so that it adds a slash at the end of the line if it is not there?
For example:
Bad: http://localhost/example/author/admin
Good: http://localhost/example/author/admin/

Bad: http://localhost/example/author/admin?query=1212
Good: http://localhost/example/author/admin/?query=1212

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dodo512, 2022-02-19
@indeveloping

clean_url = url.replace(/($|\?)/, "/$1").replace(/([^:]\/)\/+/g, "$1")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question