且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在字符串中的每个字符之间添加空格?

更新时间:2022-05-22 08:19:07

你可以使用 split() 函数将字符串转换为单个字符数组,并且然后 join() 函数将其转换回指定连接的字符串g字符(指定空格作为连接字符):

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(" ");
}

(注意参数 split()是你要分割的字符,例如,你可以使用 split(,)来分解以逗号分隔的列表,但是如果你传递一个空字符串,它只会拆分每个字符。)

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