Reputation: 28168
I currently have a long pathname storedin var imgSrc
The var is a full web address, e.g http://mywebsite.co.uk/fyp/login-register/images/avatars/16.png
I want to grab only the section up until the last slash, so only store 16.png
, and then remove the last .png
I tried using a trim()
function but am not sure how to use the \
as the delimiter for the trim.
Once I have done this I then need to take the last 3 chars of, so return only the number.
E.g I need to go from
http://www.myurl.com/images/something/16.png
All the way down to:
16
I think I have that last part covered by slice
:
var srcID = imgSrc.slice(0,3);
web address length is not always the same, so it needs to rely on using \
instead of using specific hardcoded numbers
Upvotes: 0
Views: 157
Reputation: 318322
How about splitting by /
, getting the last part and keeping just the numbers.
var srcID = imgSrc.split('/').pop().replace(/\D/g,'');
Upvotes: 1
Reputation: 3572
var srcID = imgSrc.substr(imgSrc.lastIndexOf('/')).match(/[\w\d]+/)[0];
srcID
will equal 16
.
You'll want to avoid the slice()
method because it'll only work if the image's filename is two characters long.
Upvotes: 0
Reputation: 196
To get only the last "16.png", you can try with
var last = imgSrc.substr(imgSrc.lastIndexOf('/') + 1);
Upvotes: 0
Reputation: 401
The lazy person's string manipulation:
Use the "split" method to break a string up into an array, hinging at whatever character:
var urlPieces = imgSrc.split( "/" ),
lastUrlPiece = urlPieces[ urlPieces.length - 1 ],
filenamePieces = lastUrlPiece.split( "." ),
filenameSansExtension = filenamePieces[ 0 ];
:)
Upvotes: 0
Reputation: 207983
With a regex:
var str ="http://www.myurl.com/images/something/16.png";
var found = str.match(/\d+/);
console.log(found[0]);
Upvotes: 1
Reputation:
You could 'split' the data:
var url = 'http://mywebsite.co.uk/fyp/login-register/images/avatars/16.png';
var arr = url.split('/');
var last = arr.length - 1;
var pic = arr[last].split('.');
//--- image name in now in pic[0
]
Upvotes: 1