Home > Enterprise >  get img src string portion between 2 items
get img src string portion between 2 items

Time:10-22

using the example here

<img src="site.com/player_photos_big_2014/11247_thumb.jpg" class="articlepicture">
<img src="site.com/player_photos_big_2014/5666_thumb.jpg" >
<img src="site.com/player_photos_big_2014/76893_thumb.jpg" >

I'm wanting to get the digits of "11247" , "5666" , "76893"

Tried this and didn't work , the image thumb names are different and could be 3 to 5 numerical numbers

var test= $('.articlepicture').attr('src')
test.match(/player_photos_big_2014/(. ?)_thumb.jpg)[1]

CodePudding user response:

Try using split("/").at(-1) to get the last string (11247_thumb.jpg), then use replace("_thumb.jpg", "") to get just the number as a string, lastly; if you want it as an int, use parseInt() or Number()

All combined should look something like this:

let playerNum = parseInt($(".articlepicture").attr("src").split("/").at(-1).replace("_thumb.jpg", ""))
console.log(playerNum)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="site.com/player_photos_big_2014/11247_thumb.jpg" class="articlepicture">
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Of course this will only work if the filenames are consistent though!

CodePudding user response:

Regexp \/(\d ) to match the /123456 part and (\d ) to extract the number part

document.querySelectorAll('img.articlepicture').forEach(img => {
  const n = (img.getAttribute('src').match(/\/(\d ).*\.jpg$/) || ['',''])[1];
  console.log(n);
});
<img src="site.com/player_photos_big_2014/11247_thumb.jpg" class="articlepicture">
<img src="site.com/player_photos_big_2014/5666_thumb.jpg" class="articlepicture">
<img src="site.com/player_photos_big_2014/76893_thumb.jpg" class="articlepicture">
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Can you try this ?

test.match(\/player_photos_big_2014\/(. ?)_thumb\.jpg)[1]

Some characters must be escaped

Also, you can test your regex with some sites like this, they are really cool: https://regex101.com

  • Related