0

I have a word such as

var text = 'http://xxx:9696/images/FSDefault.jpg';

How to get only the word FSDefault.jpg

Pawan
  • 31,545
  • 102
  • 256
  • 434

2 Answers2

7

Use String#split method to split based on delimiter / and get the last element of the array using Array#pop method.

var text = 'http://xxx:9696/images/FSDefault.jpg';

console.log(text.split('/').pop())


Or you can use String#lastIndexOf method along with String#substr method.

var text = 'http://xxx:9696/images/FSDefault.jpg';

console.log(text.substr(text.lastIndexOf('/') + 1))
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • Interestingly it seems like the String.lastIndexOf() actually performs better than the other options: https://jsperf.com/last-item-in-string – Jani Hyytiäinen Nov 02 '16 at 09:48
0

This is pretty verbose but conveys the logic.

var text = 'http://xxx:9696/images/FSDefault.jpg';
var parts = text.split('/'); // Split the string into an array of strings by character /
var lastIndexOf = parts.length - 1; // Determine the last word's 0-based index in array (length -1) 
var last = parts[lastIndexOf]; // Grab the last part of the array.
alert(last); // Alerts FSDefault.jpg
Jani Hyytiäinen
  • 5,293
  • 36
  • 45