2

I have a DataTable which is being populated by JSON. The days of the week (for example) are returning as a string which i am applying .split(',') to and is working in my forEach function, but i need to apply a class to my days returned buttons but due to the space in the string it only falls into my 'Mon' button and not the rest due to the space.

Working code

var selectedDays = modifyRecordData.selectedDays;
var splitSelectedDays = selectedDays.split(',');
console.log(splitSelectedDays);

splitSelectedDays.forEach(day => {
  if(day == 'Mon') {
    alert('in Mon')
    $('#mon').removeClass('btn-default');
    $('#mon').addClass('btn-primary');
  }

  if (day == 'Tue') {
    alert('in Tue')
    $('#tue').removeClass('btn-default');
    $('#tue').addClass('btn-primary');
  }

  // AND SO ON
})

This also returns

enter image description here

I have tried the following but none are working

var selectedDays = modifyRecordData.selectedDays;
var splitSelectedDays = selectedDays.split(',').trim();

and

var selectedDays = modifyRecordData.selectedDays;
var splitSelectedDays = selectedDays.split(',').trim();
var test = splitSelectedDays.trim();

also thruught about trying in the actual loop as each one returned as a string using the below

splitSelectedDays.forEach(day => {
      splitSelectedDays.trim();

But always get the function error.

I am wanting to remove the space, then lowercase the value then i can use the var in on addClass function rather than an IF for each day of the week

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
murday1983
  • 3,806
  • 14
  • 54
  • 105
  • You can't `trim()` an array. Only a string. See the duplicate for how to apply trim to all the strings in an array. This answer specifically: https://stackoverflow.com/a/41183617/519413 – Rory McCrossan Mar 01 '19 at 09:02

2 Answers2

5

split in selectedDays.split(',').trim(); will create an array. There is no trim for array. So you can iterate the array and apply trim if it is a string

You can do like this

splitSelectedDays.forEach(day => {
  let val = day.trim();
  // rest of the code
})
brk
  • 48,835
  • 10
  • 56
  • 78
2

var splitSelectedDays = selectedDays.split(',').trim();

This is your problematic line.

selectedDays.split(',') will return an array of strings. Trim is a method on a string, not an array of strings, that removes leading/trailing whitespace.

You will have to apply trim() to each individual element in the array.

For example

var splitSelectedDays = selectedDays.split(',');

for (var i=0; i < splitSelectedDays.length; i++)
{
    splitSelectedDays[i] = splitSelectedDays[i].trim();
}
NibblyPig
  • 51,118
  • 72
  • 200
  • 356