0

I tried to extract the Only URL part not the Path, for example

if the url is https://example.com/news/cricket

the output should be https://example.com/

but i am not strong on regular expression.

data = "https://example.com/news/cricket";
var name = data.substring(0, data.lastIndexOf("/"));
console.log(name);

this is what i have tried but output is:-

https://example.com/news

Expected output is

https://example.com/

Thank for healping guys

RAJENDRA H
  • 83
  • 10

1 Answers1

0

lastIndexOf() returns the index of the last /, which is the one before cricked, not before news.

indexOf() takes an optional starting index, you can first search for // and then search for the next / after that.

You need to add 2 to the index of // to skip over it. And you have to add 1 to the index of / so you include the / in the result.

data = "https://example.com/news/cricket";
var name = data.substring(0, data.indexOf("/", data.indexOf("//")+2)+1);
console.log(name);

With a regexp, use a regexp that matches up to the first // and then to the next /.

var data = "https://example.com/news/cricket";
var match = data.match(/^.*?\/\/.*?\//);
if (match) {
  var name = match[0];
  console.log(name);
}
Barmar
  • 741,623
  • 53
  • 500
  • 612