-1

$('button').on('click', function(){
var str = $.map($('.bimg'), (e) => $(e).attr('src')).join(',');
console.log(str);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class='bimg' src='gall/lorem.jpg' alt='img'>
<img class='bimg' src='gall/ipsum.jpg' alt='img'>
<img class='bimg' src='gall/dolor.jpg' alt='img'>
<button>CLICK</button>

Result:

gall/lorem.jpg,gall/ipsum.jpg,gall/dolor.jpg

What I need:

lorem,ipsum,dolor
0stone0
  • 34,288
  • 4
  • 39
  • 64
qadenza
  • 9,025
  • 18
  • 73
  • 126
  • Use this `var str = $.map($('.bimg'), (e) => $(e).attr('src').split('/')[1].split('.')[0]).join(',')` Or you can use regex `var str = $.map($('.bimg'), (e) => $(e).attr('src').match(/\/(.*)\.jpg/)[1])` – Hassan Imam Sep 20 '21 at 11:32
  • 1
    Does this answer your question? [How to trim a file extension from a String in JavaScript?](https://stackoverflow.com/questions/4250364/how-to-trim-a-file-extension-from-a-string-in-javascript) – 0stone0 Sep 20 '21 at 11:36
  • @0stone0 - is not just a trim of an extension - there is also folder part and also I need it using `map` – qadenza Sep 20 '21 at 11:39
  • *Basic* extrapolating from @0stone0 's linked answer gives: `var x = $(e).attr('src'); x.substring(x.lastIndexOf('/')+1, x.lastIndexOf('.'))` – freedomn-m Sep 20 '21 at 11:42
  • @freedomn-m - it's ok for one single image. I have a lot of them, and want to avoid loop – qadenza Sep 20 '21 at 11:45
  • 1
    Put that inside the .map... where you have `$(e)` https://jsfiddle.net/3Lcth4y0/ – freedomn-m Sep 20 '21 at 11:46

2 Answers2

1

Add the following to your map

.split('/').pop().split('.').shift()

So we split on each / and use pop() to get the last one found

Then we'll split on each . and use shift() to get the first part

$('button').on('click', function(){
    var str = $.map($('.bimg'), (e) => $(e).attr('src').split('/').pop().split('.').shift()).join(',');
    console.log(str);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class='bimg' src='gall/lorem.jpg' alt='img'>
<img class='bimg' src='gall/ipsum.jpg' alt='img'>
<img class='bimg' src='gall/dolor.jpg' alt='img'>
<button>CLICK</button>

lorem.jpg,ipsum.jpg,dolor.jpg

0stone0
  • 34,288
  • 4
  • 39
  • 64
1

You can use regex to get the image name from src.

$('button').on('click', function() {
  var str = $.map($('.bimg'), (e) => $(e).attr('src').match(/\/(.*)\.jpg/)[1]).join(',')
  console.log(str);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class='bimg' src='gall/lorem.jpg' alt='img'>
<img class='bimg' src='gall/ipsum.jpg' alt='img'>
<img class='bimg' src='gall/dolor.jpg' alt='img'>
<button>CLICK</button>
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51