How to add spaces between every character in a string?

后端 未结 4 1505
盖世英雄少女心
盖世英雄少女心 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:33
    function insertSpaces(aString)
    {
      return aString.split('').join(' ');
    }
    
    0 讨论(0)
  • 2020-12-06 19:35

    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
    
    0 讨论(0)
  • 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.)

    0 讨论(0)
  • 2020-12-06 19:46

    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.

    0 讨论(0)
提交回复
热议问题