Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add spaces between every character in a string?

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, separated by space characters.

E.g.

Hello

becomes

H e l l o

I'm a massive novice and I'm sure that this might seem like a no-brain'er to some people, but I just can't seem to get my head around it.

like image 930
Ross Cheeseright Avatar asked Sep 10 '11 13:09

Ross Cheeseright


2 Answers

You can use the split() function to turn the string into an array of single characters, and then the join() function to turn that back into a string where you specify a joining character (specifying space as the joining character):

function insertSpaces(aString) {
  return aString.split("").join(" ");
}

(Note that the parameter to split() is the character you want to split on so, e.g., you can use split(",") to break up a comma-separated list, but if you pass an empty string it just splits up every character.)

like image 162
nnnnnn Avatar answered Oct 16 '22 13:10

nnnnnn


That's quite easy... just call the replace method on the string as follow...

var str = "Hello";
console.info(str.replace(/\B/g, " ");

What am I doing here is replacing on non-word boundary which is inside the word. It's just reverse of the word boundary denoted by "\b", which is around the word; think it as if you are matching the border of the word.

like image 25
Manvendra SK Avatar answered Oct 16 '22 11:10

Manvendra SK