gpt4 book ai didi

javascript - 删除字符不匹配的字符串开头

转载 作者:行者123 更新时间:2023-12-03 01:22:33 24 4
gpt4 key购买 nike

假设我有这个网址:

git+https://github.com/ORESoftware/npp.git

我想删除第一个与“http”不匹配的字符。我还想删除 .git,但不确定如何可靠地做到这一点。

所以我希望得到这个字符串:

https://github.com/ORESoftware/npp

作为一个全面的侧面对话,不确定该网址与以下内容有何不同:

www.github.com/ORESoftware/npp

最佳答案

你可以试试这个:

let s = 'git+https://github.com/ORESoftware/npp.git';
console.log(s.replace(/^.*?(http.*?)\.git$/, '$1'))

输出:

https://github.com/ORESoftware/npp

该正则表达式的工作原理如下:

^.*? 是从字符串开头到下一个匹配元素的非贪婪匹配,在本例中为 (http.*?) 捕获组。

(http.*?) 是一个捕获组,它捕获从 http 到下一个匹配的所有内容(因为 .*? 是再次非贪婪)

\.git$ 与字符串中的尾随 .git 匹配。

替换字符串$1仅用捕获组的内容替换原始字符串的内容。在本例中,这是从 http.git 之前的最后一个字符的所有内容。

关于javascript - 删除字符不匹配的字符串开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51699214/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com