get last string after / in javascript
- Published
- Reading time
- 2 min read
- Length
- 350 words
On this page
Get last string after / in JavaScript#
If you are working with JavaScript, you may need to extract the last string after a forward slash from a URL or any other string. There are multiple ways to achieve this task in JavaScript. Let's explore them one by one.
Using the split() method#
The easiest way to extract the last string after a forward slash is to use the split() method. Here's how you can do it:
let url = 'https://example.com/blog/last-string';
let parts = url.split('/');
let lastPart = parts[parts.length - 1];
console.log(lastPart); // Output: last-stringIn this code, we first define a URL and then split it into an array of strings using the forward slash as a separator. We then extract the last element of the array using the index parts.length - 1. This gives us the last string after the forward slash.
Using the substring() method#
Another way to extract the last string after a forward slash is to use the substring() method. Here's how you can do it:
let url = 'https://example.com/blog/last-string';
let lastPart = url.substring(url.lastIndexOf('/') + 1);
console.log(lastPart); // Output: last-stringIn this code, we first define a URL and then use the lastIndexOf() method to find the index of the last forward slash in the URL. We then add 1 to this index to get the starting index of the last string. Finally, we use the substring() method to extract the last string.
Using the replace() method#
You can also use the replace() method to extract the last string after a forward slash. Here's how:
let url = 'https://example.com/blog/last-string';
let lastPart = url.replace(/^.*\/([^/]*)$/, '$1');
console.log(lastPart); // Output: last-stringIn this code, we use a regular expression to match the last string after the forward slash. The replace() method replaces the whole URL with the last string using the matched group $1.
Summary#
These were some of the ways you can extract the last string after a forward slash in JavaScript. Depending on your use case and preference, you can choose any of these methods.