I am trying to create a function that inserts spaces between the characters of a string argument then return a new string which contains the same characters as the argument,
Alternative for a split and join solution could be:
'Hello'.replace(/(.(?!$))/g,'$1 '); //=> H e l l o
// ^all characters but the last
// ^replace with found character + space
Or in a function:
function insertChr(str,chr) {
chr = chr || ' '; //=> default is space
return str.replace(/(.(?!$))/g,'$1'+chr);
}
//usage
insertChr('Hello'); //=> H e l l o
insertChr('Hello','-'); //=> H-e-l-l-o
or as a String prototype function:
String prototype.insertChr(chr){
chr = chr || ' '; //=> default is space
return this.replace(/(.(?!$))/g,'$1'+chr);
}
//usage
'Hello'.insertChr(); //=> H e l l o
'Hello'.insertChr('='); //=> H=e=l=l=o