How to add spaces between every character in a string?

后端 未结 4 1518
盖世英雄少女心
盖世英雄少女心 2020-12-06 19:07

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,

4条回答
  •  心在旅途
    2020-12-06 19:40

    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.)

提交回复
热议问题