My first guess is something like this would work.
var underscored = string.split('').map(function(char) {
return char = '_ ';
}).join('');
Get every character in the string with the split
function, and change the state of every character, using the map
function. However, this will just give us an array. We need to perform type conversion again to turn it back to a string. To do this, we can use the join
method. The delimiter we join is simply an empty string ''
.
Another possibility is with the replace function
var underscored = string.replace(/./g, '_ ');
The regular expression here is very simple. The period .
indicates any character. The global(g)
flag means find all instances of the previous regex.
The second parameter of this function is what we want these characters to become. Since we want a space between underscores, this will be _
.
Note that the replace
method is not destructive. In other words, it does not modify the original array. You would need to store this in a separate variable. Because if you call string
again, kaiser
will be returned.