简体   繁体   中英

Remove beginning of string where characters do not match

Say I have this url:

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

I want to remove the first characters that do not match "http". I also want to remove the .git, but not sure how to do that reliably.

So I am looking to get this string:

https://github.com/ORESoftware/npp

as a total side conversation, not sure how that url differs from:

www.github.com/ORESoftware/npp

You could try this:

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

Output:

https://github.com/ORESoftware/npp

This regex works as follows:

^.*? is a non-greedy match from the beginning of the string until the next element which does match, in this case the (http.*?) capturing group.

(http.*?) is a capturing group which captures everything from the http until the next match (since .*? is again non-greedy)

\\.git$ matches a trailing .git on the string.

The replacement string $1 replaces the contents of the original string with only the contents of the capturing group. In this case that is everything from http until the last character before .git .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM