George Zafiris George Zafiris - 7 months ago 10
Javascript Question

JavaScript - Insert an element to an array without affecting the indexes?

I'm working on a problem like this for sometime now, trying to figure out what to do with the indexes. Here's the problem:

I have a string:

thisIsGreat

The basic operations used are bellow:

var str = "thisIsGreat";
str = str.split(''); //Making it an array
.....
str = str.join(''); //String it back again
console.log(str);


Desired Output:
["t","h","i","s"," ","I","s"," ","G","r","e","a",t"]


I'm having hard time inserting spaces between those words without affecting the indexes. I tried something like this, but it didn't work.

for (var i = 0; i < str.length; i++){
if (str[i]+1 == (str[i].toUpperCase())+1)
str[i] = " ";
}


Is there a way to fix this? Any thoughts?

Answer

You could use a replace with positive lookahead.

var str = "thisIsGreat";
    str = str.replace(/(?=[A-Z])/g, ' ').split('');

document.write('<pre>' + JSON.stringify(str, 0, 4) + '</pre>');