Friday, October 17, 2025
HomeLanguagesJavascriptHow to get value of a string after last slash in JavaScript?

How to get value of a string after last slash in JavaScript?

The task is to get the string after a specific character(‘/’). Here are a few of the most used techniques discussed. We are going to use JavaScript. 

Approach 1:

  • Split the string by .split() method and put it in a variable(array).
  • Use the .length property to get the length of the array.
  • From the array return the element at index = length-1.

Example: This example uses the approach discussed above. 

Javascript




let str = "folder_1/folder_2/file.html";
 
function GFG_FUN() {
     
    str = str.split("/");
 
    console.log(str[str.length - 1]);
}
 
GFG_FUN();


Output

file.html

Approach 2:

Example: This example uses the approach discussed above. 

Javascript




let str = "folder_1/folder_2/file.html";
 
function GFG_FUN() {
    console.log(str.substring(str.lastIndexOf('/') + 1));
}
 
GFG_FUN();


Output

file.html

Approach 3:

Example: This example uses the above approach

Javascript




let str = "folder_1/folder_2/file.html";
 
function GFG_FUN() {
    str = str.split("/").pop();
    console.log(str);
}
 
GFG_FUN();


Output

file.html

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS