0

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.

1
  • Will your URL always end with .html? Commented Mar 10, 2018 at 10:28

4 Answers 4

3

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);

Sign up to request clarification or add additional context in comments.

2 Comments

I would highlight the second use case. It makes it stand out as a more viable answer!
It's better to expand match scope of second regex: /([^/?&#]+)(?![^/]*/)
3

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)

Comments

1

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);

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.