如何在字符串中的每个字符之间添加空格? [英] How to add spaces between every character in a string?

查看:332
本文介绍了如何在字符串中的每个字符之间添加空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个在字符串参数的字符之间插入空格的函数,然后返回一个新的字符串,其中包含与参数相同的字符,用空格字符分隔。

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.

例如

Hello

变为

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.

推荐答案

你可以使用 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.)

这篇关于如何在字符串中的每个字符之间添加空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆