Balázs Orbán Balázs Orbán - 1 year ago 143
Javascript Question

Substr on an array element if not empty

Hei, I have an array containing some empty strings and some strings with content.

I want to slice down the first 5 letters of those which are not empty strings, and put them into a new array. I also want to keep the empty ones.


myArray = [ "","","123456789","","",""];
var newArray = ["","","12345","","",""]

I tried with for loop with if inside if the myArray[i] is empty then don't do substr(), but I get an error that it is not a function.

I actually don't need to put it into a new array, I just want to put the myArray(i).subsrt(5) value into a splice(), but then I get the error:

VM750:82 Uncaught TypeError: Cannot read property 'substr' of undefined

Answer Source

ES6 with

myArray = [ "","","123456789","","",""];
var newArray = => s.substr(0, 5))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download