Search code examples
jqueryimagepathstrip

How can I get stripped image name using jQuery?


Let's say I have an img element with src="img/highlow.png".

How can strip down to get alert('highlow');?


Solution

  • You need to find the image, use prop (or attr if you have jQuery 1.5 or below) to get the src property, then regex to get the part you want.

    Your code might look like this:

    alert($('#yourImageId').prop('src').match(/(\w*)\.\w{3,4}$/)[1]);
    

    This assumes that the image has no non-word characters (i.e. it's only A-Za-z0-9_) and that its file extension is 3 or 4 characters long. If this isn't correct, you'll have to modify it.