Yaroslav Saenko
Yaroslav Saenko

Reputation: 587

URL last part regular expression

I need to get the last part of my URL with html on the end. So if I have this url http://step/build/index.html I need to get only index.html. I need to do this with javascript

let address = http://step/build/index.html;
let result = address.match(/html/i);

I tried this, but it doesn't work for me, maybe I make some mistakes. How do I get the last segment of URL using regular expressions Could someone help me and explain it in details? Thank you.

Upvotes: 0

Views: 509

Answers (4)

The fourth bird
The fourth bird

Reputation: 163207

You could use split which returns an array to split on a forward slash and then use pop which removes the last element from the array and returns that:

let address = "http://step/build/index.html".split('/').pop();
console.log(address);

If you have querystring parameters which could for example start with ? or #, you might use split again and get the first item from the array:

let address2 = "\"http://step/build/index.html?id=1&cat=2"
  .split('/')
  .pop()
  .split(/[?#]/)[0];
console.log(address2);

Upvotes: 1

Jeto
Jeto

Reputation: 14927

Here's a non-regex approach. Should be more reliable/appropriate at the job, depending on whether you'll need other URL-specific parts:

// Note the ?foo=bar part, that URL.pathname will ignore below
let address = 'http://step/build/index.html?foo=bar';

let url = new URL(address);

// Last part of the path
console.log(url.pathname.split('/').pop());
// Query string
console.log(url.search);
// Whole data
console.log(url);

Upvotes: 1

Sjoerd de Wit
Sjoerd de Wit

Reputation: 2413

You could split it on slashes and then fetch the last item:

let address = "http://step/build/index.html";
let result = address.split("/").pop();
console.log(result)

Upvotes: 3

Vivek
Vivek

Reputation: 2755

You can extract the .html filename part using this /[^/]+\.html/i RegEx.

See the code below.

const regex = /[^/]+\.html/i;

let address = "http://step/build/index.html";
let result = address.match(regex);
console.log(result);

The same RegEx will also match the filename incase the URL has additional parameters.

const regex = /[^/]+\.html/i;

let address = "http://step/build/index.html?name=value";
let result = address.match(regex);
console.log(result);

Upvotes: 3

Related Questions