Javascript find protocol, domain, plus first slash with regex from src tag, replace with empty string

I tried to create a regex for this task, but I'm afraid I still can't get an intuitive understanding of regexp.

The problem is matching regular expressions to the last slash in the string. I want it to stop at the first match of the string.

My pathetic attempt to regex:

/^http(s?):\/\/.+\/{1}/

Test Subject:

http://foo.com/bar/test/foo.jpeg

The goal is to get bar/test/foo.jpegit so that I can then break the line, pull out the last element and then join the remainder, resulting in a path to the JavaScript file.

Example

var str = 'http://foo.com/bar/test/foo.jpeg';
str.replace(regexp,'');
+4
source share
2 answers

, , , .

, .+ , greedily, .. , regex ( / ). , http /.

http /, .+ [^/]+.

^https?:\/\/[^\/]+\/
            ^^^^^^

- regex

, s , , unescaped ? - , . , {1} , , c 1 c, (?:something) something.

var re = /^https?:\/\/[^\/]+\//; 
var str = 'http://foo.com/bar/test/foo.jpeg';
var result = str.replace(re, '');
document.getElementById("r").innerHTML = result;
<div id="r"/>
Hide result

, , JS .

Regex:

  • ^ -
  • https? - http, https
  • :\/\/ - ://
  • [^\/]+ - 1 , /
  • \/ - /
+3

.

> var s = "http://foo.com/bar/test/foo.jpeg"
> s.match(/^https?:\/\/[^\/]+((?:\/[^\/]*)*)/)[1]
'/bar/test/foo.jpeg'
+2

Source: https://habr.com/ru/post/1622422/


All Articles