TransWikia.com

How to remove first comma when pushing inside input value with split(',')?

Stack Overflow Asked on November 22, 2021

I have an issue with split() function, I have input in which I push ids that I’m getting through mapping objects.

My HTML:

<input class="custom-img-id" name="custom-img-id" type="hidden" value="" />

My JS:

frame.on( 'select', function() {
  var imgIdInput = $( '.custom-img-id' );

  var attachments = frame.state().get('selection').map(function( a ) {
    a.toJSON();
    return a;
  }),
  thesamepicture = false,
  i;

  for (i = 0; i < attachments.length; ++i) {
      imgContainer.append('<img src="' + attachments[i].attributes.url + '"/>');
      
      imgIdInput.val().split(",").push( attachments[i].id );
  }
  imgIdInput.val( imgIdInput.val().split(",").join() );
});

If for example I have two object with ids 100 and 101, I will get inside input value this:

value=",100,101"

How to remove first comma? I think I’m doing something wrong.

3 Answers

You need to use split, filter and join function of the array & String to get the expected output.

var value=",100,101"

value = value.split(",")

const finalValue = value.filter(tmp =>{
return tmp !== ''
})

console.log(finalValue.join(","));

Answered by Rajan on November 22, 2021

The issue is probably that "".split(",") gives you [""], not an empty array.

I'd suggest splitting the string once prior to the loop (handling the issue with ""), adding to the resulting array, and then converting it back to a string once at the end, see *** comments:

frame.on( 'select', function() {
  var imgIdInput = $( '.custom-img-id' );

  var attachments = frame.state().get('selection').map(function( a ) {
    a.toJSON();
    return a;
  }),
  thesamepicture = false,
  i;

  // *** Get the current IDs as an array
  var val = imgIdInput.val().trim();
  var ids = val ? imgIdInput.val().split(",") : [];
  for (i = 0; i < attachments.length; ++i) {
      imgContainer.append('<img src="' + attachments[i].attributes.url + '"/>');
      
      // *** Add to the array
      ids.push(attachments[i].id);
  }
  // *** Save the IDs in the hidden input
  imgIdInput.val(ids.join());
});

Answered by T.J. Crowder on November 22, 2021

you can use replace

imgIdInput.val( imgIdInput.val().split(",").join().replace(",","") );


console.log(",100,101".replace(",",""))  // "100,101"

Answered by Moufeed Juboqji on November 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP