|
1 | | -const useHash = process.env.VITE_REACT_APP_USE_HASH_LINKS === "true" || false; |
| 1 | +const _useHash = process.env.VITE_REACT_APP_USE_HASH_LINKS === "true" || false; |
2 | 2 |
|
3 | 3 | const localReplaceLink = (url, locale) => { |
4 | | - if (url) { |
5 | | - if (!url.substr(url.indexOf("/wp") + 3).startsWith("/" + locale)) { |
6 | | - return "/" + locale + url.substr(url.indexOf("/wp") + 3); |
| 4 | + if (!url) { |
| 5 | + return ""; |
| 6 | + } |
| 7 | + const safeLocale = locale || "en"; |
| 8 | + |
| 9 | + try { |
| 10 | + let pathname = url; |
| 11 | + |
| 12 | + // If absolute URL, extract pathname and ignore origin |
| 13 | + if (/^https?:\/\//i.test(url)) { |
| 14 | + const parsed = new URL(url); |
| 15 | + pathname = parsed.pathname + (parsed.search || "") + (parsed.hash || ""); |
7 | 16 | } |
8 | | - return url.substr(url.indexOf("/wp") + 3); |
| 17 | + |
| 18 | + if (!pathname.startsWith("/wp/")) { |
| 19 | + return url; // Not a WordPress path, leave unchanged |
| 20 | + } |
| 21 | + |
| 22 | + const afterWp = pathname.slice(3); // remove '/wp' |
| 23 | + |
| 24 | + if (!afterWp.startsWith("/" + safeLocale)) { |
| 25 | + return "/" + safeLocale + afterWp; |
| 26 | + } |
| 27 | + |
| 28 | + return afterWp; |
| 29 | + } catch (e) { |
| 30 | + console.error("Error parsing URL:", e); |
| 31 | + return url; |
9 | 32 | } |
10 | | - return ""; |
11 | 33 | }; |
12 | 34 |
|
13 | 35 | export const replaceLink = (url, locale) => { |
14 | | - return localReplaceLink(url, locale) |
| 36 | + if (!url) { |
| 37 | + return ""; |
| 38 | + } |
| 39 | + return localReplaceLink(url, locale); |
15 | 40 | } |
16 | 41 |
|
17 | 42 | export const replaceHTMLinks = (html, locale) => { |
18 | 43 | //console.log("--------- replaceHTMLinks--------------") |
19 | 44 | // console.log(process.env.REACT_APP_WP_HOSTS) |
20 | 45 |
|
21 | 46 | let link; |
22 | | - let regex = /href\s*=\s*(['"])(https?:\/\/.+?)\1/ig; |
| 47 | + // Match both absolute (http/https) and relative WP links in a single pass |
| 48 | + let linkRegex = /href\s*=\s*(['"])(https?:\/\/.+?|\/wp\/[^'"\s>]+)\1/ig; |
23 | 49 |
|
24 | 50 | let newHtml = html |
25 | | - while ((link = regex.exec(html)) !== null) { |
| 51 | + while ((link = linkRegex.exec(html)) !== null) { |
26 | 52 | let href = link[2] |
27 | 53 | let newLink = localReplaceLink(href, locale) |
28 | | - newHtml = newHtml.replaceAll(link[2], newLink) |
| 54 | + if (newLink !== href) { |
| 55 | + newHtml = newHtml.replaceAll(href, newLink) |
| 56 | + } |
29 | 57 | } |
30 | 58 | return newHtml; |
31 | 59 | } |
|
0 commit comments