Adding Elements in An Array Incrementally Using Splice Javascript -


i'm trying add "-" before capital letters. e.g. helloworld becomes hello-world.

my code, however, placing "-" in array @ wrong places. i.e. thisisspinaltap becomes this-i-sspin-altap

what's wrong code?

function spinalcase(str){ str = str.replace(/ /g,'-'); strarr = str.split(""); for(i=1;i<str.length;i++){     if(str.charat(i)==str.charat(i).touppercase()&&str.charat(i)!=="-"){         console.log(i);         strarr.splice(i,0,"-");     } }  return strarr.join(""); }  spinalcase('thisisspinaltap'); // returns this-i-sspin-altap  

what's wrong every time splice, strarr drifts left; ideally should keep counter starts @ 0 , increases whenever splice, e.g.:

var k = 0; // ...     strarr.splice(i + k, 0, '-');     ++k; 

assuming you're not doing exercise, easier way:

var s = 'thisisspinaltap';  var res = s.replace(/([a-z])([a-z])/g, '$1-$2'); // "this-is-spinal-tap" 

the expression matches lowercase letter followed uppercase letter , replaces dash in between.


Comments