我想替換一部分的url:
Origin-> https://example.u-test.com/ex-2< br>
目的地-> https://example.u-test.com/ex <br>
因此,我想洗掉"-"后面的部分,但只在第一個斜線后的第二部分。
用url.replace(/ *-[^.]*. */g, ".")/code>我得到:
我想洗掉ex后面的"-2",而不是第一部分的"-test"。
什么是正確的regex運算式?
uj5u.com熱心網友回復:
你可以使用URL介面來實作。它允許你輕松地讀取和修改一個給定的URL的不同組件。
const url = new URL("https://example.u-test.com/ex-2");
const domain = url.hostname。
const pathname = url.pathname;
const part = pathname.split("-")[0] 。
console.log(domain part);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
如果你絕對想用正則運算式來做這件事:
const url = "https://example.u-test.com/ex-2"
const result = url.replace(/-[^-]*$/g, " ")
console.log(result)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
解釋:
如果你想洗掉最后一個斜線或破折號之后的部分,你應該從這個點開始匹配。上面的正則運算式從該行的最后一個破折號(-)字符開始匹配。Regex將只匹配最后一個破折號,因為它搜索的后續字符是除了另一個破折號之外的所有字符,然后是行尾($)。
-匹配一個破折號(-)字符[^-]*匹配除了另一個破折號以外的所有字符$在破折號和非破折號字符之后,必須有行尾 。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/320516.html
標籤:
