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 few of the mostly 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 1: This example using the approach discussed above.
<!DOCTYPE HTML> < html > < head > < title > Get value of a string after last slash in JavaScript? </ title > </ head > < body style = "text-align:center;" id = "body" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style="font-size: 15px; font-weight: bold;"> </ p > < button onclick = "GFG_FUN()" > click here </ button > < p id = "GFG_DOWN" style="font-size: 24px; font-weight: bold; color: green;"> </ p > < script > var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var str = "folder_1/folder_2/file.html"; el_up.innerHTML = "Click on the button to get"+ " the string after last slash.< br >< br >String - '" + str + "'"; function GFG_FUN() { str = str.split("/"); el_down.innerHTML = str[str.length - 1]; } </ script > </ body > </ html > |
Output:
- Before clicking on the button:
- After clicking on the button:
Approach 2:
- First, find the last index of (‘/’) using .lastIndexOf(str) method.
- Use the .substring() method to get the access the string after last slash.
Example 2: This example using the approach discussed above.
<!DOCTYPE HTML> < html > < head > < title > Get value of a string after last slash in JavaScript? </ title > </ head > < body style = "text-align:center;" id = "body" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style="font-size: 15px; font-weight: bold;"> </ p > < button onclick = "GFG_FUN()" > click here </ button > < p id = "GFG_DOWN" style="font-size: 24px; font-weight: bold; color: green;"> </ p > < script > var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var str = "folder_1/folder_2/file.html"; el_up.innerHTML = "Click on the button to get"+ " the string after last slash.< br >< br >String - '" + str + "'"; function GFG_FUN() { el_down.innerHTML = str.substring(str.lastIndexOf('/') + 1); } </ script > </ body > </ html > |
Output:
- Before clicking on the button:
- After clicking on the button: