diff --git a/app/assets/javascripts/discourse-common/addon/lib/get-url.js b/app/assets/javascripts/discourse-common/addon/lib/get-url.js index 29a9e56ce14..b15ed2c5ba4 100644 --- a/app/assets/javascripts/discourse-common/addon/lib/get-url.js +++ b/app/assets/javascripts/discourse-common/addon/lib/get-url.js @@ -1,9 +1,10 @@ -let cdn, baseUrl, baseUri; +let cdn, baseUrl, baseUri, baseUriMatcher; let S3BaseUrl, S3CDN; export default function getURL(url) { if (baseUri === undefined) { baseUri = $('meta[name="discourse-base-uri"]').attr("content") || ""; + baseUriMatcher = new RegExp(`^${baseUri}`); } if (!url) { @@ -47,18 +48,23 @@ export function isAbsoluteURL(url) { } export function withoutPrefix(path) { - const rootURL = (!baseUri ? "/" : baseUri).replace(/\/$/, ""); - return path.replace(rootURL, ""); + if (!baseUri) { + return path; + } else { + return path.replace(baseUriMatcher, ""); + } } export function setPrefix(configBaseUri) { baseUri = configBaseUri; + baseUriMatcher = new RegExp(`^${baseUri}`); } export function setupURL(configCdn, configBaseUrl, configBaseUri) { cdn = configCdn; baseUrl = configBaseUrl; baseUri = configBaseUri; + baseUriMatcher = new RegExp(`^${baseUri}`); } export function setupS3CDN(configS3BaseUrl, configS3CDN) { diff --git a/app/assets/javascripts/discourse/tests/unit/lib/get-url-test.js b/app/assets/javascripts/discourse/tests/unit/lib/get-url-test.js index 626de266790..abee3e28ea4 100644 --- a/app/assets/javascripts/discourse/tests/unit/lib/get-url-test.js +++ b/app/assets/javascripts/discourse/tests/unit/lib/get-url-test.js @@ -39,6 +39,43 @@ module("Unit | Utility | get-url", function () { assert.equal(withoutPrefix("/"), "/"); }); + test("withoutPrefix called multiple times on the same path", function (assert) { + setPrefix("/eviltrout"); + assert.equal(withoutPrefix(withoutPrefix("/eviltrout/hello")), "/hello"); + assert.equal(withoutPrefix(withoutPrefix("/eviltrout/")), "/"); + assert.equal(withoutPrefix(withoutPrefix("/eviltrout")), ""); + + setPrefix(""); + assert.equal( + withoutPrefix(withoutPrefix("/eviltrout/hello")), + "/eviltrout/hello" + ); + assert.equal(withoutPrefix(withoutPrefix("/eviltrout")), "/eviltrout"); + assert.equal(withoutPrefix(withoutPrefix("/")), "/"); + + setPrefix(null); + assert.equal( + withoutPrefix(withoutPrefix("/eviltrout/hello")), + "/eviltrout/hello" + ); + assert.equal(withoutPrefix(withoutPrefix("/eviltrout")), "/eviltrout"); + assert.equal(withoutPrefix(withoutPrefix("/")), "/"); + + setPrefix("/f"); + assert.equal( + withoutPrefix(withoutPrefix("/f/t/falco-says-hello")), + "/t/falco-says-hello" + ); + assert.equal( + withoutPrefix(withoutPrefix("/f/tag/fast-chain-food")), + "/tag/fast-chain-food" + ); + assert.equal( + withoutPrefix(withoutPrefix("/f/u/falco/summary")), + "/u/falco/summary" + ); + }); + test("getURL with empty paths", function (assert) { setupURL(null, "https://example.com", "/"); assert.equal(getURL("/"), "/");