[英]Replace characters of a string matched by regex
我的情況是在 HTML 頁面中找到所有有效 URL 的域名,將這些域名替換為另一個域名,但在域名內,我需要進行第二次替換。 例如,假設 url https://www.example.com/path/to/somewhere
位於 HTML 頁面中,我最終需要將其轉移到類似www-example-com.another.domain/path/to/somewhere
。
我可以進行第一次匹配並替換為以下代碼:
const regex = new RegExp('(https?:\/\/([^:\/\n\"\'?]+))', 'g');
txt = txt.replace(regex, "$1.another.domain");
但我不知道如何進行第二場比賽並替換以替換.
進入-
。 我想知道是否有任何有效的方法來完成這項任務。 我試圖做類似以下的事情,但它不起作用:
const regex = new RegExp('(https?:\/\/([^:\/\n\"\'?]+))', 'g');
txt = txt.replace(regex, "$1".replace(/'.'/g, '-') + ".another.domain");
好的 - 我想我知道你在找什么。 我會解釋它在做什么。
您有 2 個捕獲組:第一個/
之前和之后的一個。
您正在獲取第一個捕獲組,並將.
到-
您通過字符串.another.domain
添加,然后在其上附加第二個捕獲組
const address1 = 'https://www.example.com/path/to/somewhere'; const newDomain = "another.domain" const pattern = /(https?:\/\/[^:\/\n\"\'?]+)(\/.*)/; const matches = pattern.exec(address1); const converted = matches[1].replace(/\./g, "-") + `.${newDomain}${matches[2]}`; console.log(converted);
您可以使用String.prototype.replace()
的 function 版本對特定替換進行更多控制。
例如...
const txt = 'URL is https://www.example.com/path/to/somewhere' const newTxt = txt.replace(/(https?:\/\/)([\w.]+)/g, (_, scheme, domain) => `${scheme}${domain.replace(/\./g, '-')}.another.domain`) console.log(newTxt)
在這里, scheme
是第一個捕獲組(https?:\/\/)
, domain
是第二個([\w.]+)
。
如果您需要更高級的域匹配器(根據您的問題),只需替換正則表達式的那部分即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.