迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

如何在 JavaScript 中的字符串字符之间添加空格

作者:迹忆客 最近更新:2022/08/26 浏览次数:

在本文中,我们将学习如何在 JavaScript 中轻松地在字符串的字符之间添加空格。


String split() 和 Split join() 方法

要在字符串的字符之间添加空格,请在字符串上调用 split() 方法以获取字符数组,然后在数组上调用 join() 方法以使用空格分隔符连接字符。

function addSpace(str) {
  return str.split('').join(' ');
}
const str1 = 'coffee';
const str2 = 'banana';
console.log(addSpace(str1)); // c o f f e e
console.log(addSpace(str2)); // b a n a n a

字符串 split() 方法使用指定的分隔符将字符串拆分为子字符串数组。

const str1 = 'coffee,milk,tea';
const str2 = 'sun-moon-star';
console.log(str1.split(',')); // [ 'coffee', 'milk', 'tea' ]
console.log(str2.split('-')); // [ 'sun', 'moon', 'star' ]

通过使用空字符串 ('') 作为分隔符,我们将所有字符串字符拆分为单独的数组元素。

const str1 = 'coffee';
const str2 = 'banana';
// Passing an empty string ('') to the split method
// [ 'c', 'o', 'f', 'f', 'e', 'e' ]
console.log(str1.split(''));
// [ 'b', 'a', 'n', 'a', 'n', 'a' ]
console.log(str2.split(''));

字符串 join() 方法将数组中的每个字符串与分隔符组合在一起。 它返回一个包含连接数组元素的新字符串。

const arr = ['a', 'b', 'c', 'd'];
console.log(arr.join(' ')); // a b c d
console.log(arr.join('-')); // a-b-c-d
console.log(arr.join('/')); // a/b/c/d

因此,将空格字符传递给 join() 会在结果串联中用空格分隔字符。

在某些情况下,字符串已经在某些字符之间包含空格。 在这种情况下,我们的方法会在字符之间添加更多空格。

function addSpace(str) {
  return str.split('').join(' ');
}
// 这些字符串在某些字符之间有空格
const str1 = 'co  ffee';
const str2 = 'bana  na';
console.log(addSpace(str1)); // c o     f f e e
console.log(addSpace(str2)); // b a n a     n a

这是因为空格 (' ') 也是一个字符,就像一个字母,调用 split() 会使其成为数组中的一个单独元素,该元素将与其他空格组合。

// 这些字符串在某些字符之间有空格
const str1 = 'co  ffee';
const str2 = 'bana  na';
// 空格字符是从 split() 中分离出来的数组元素
/**
 * [
  'c', 'o', ' ',
  ' ', 'f', 'f',
  'e', 'e'
]
 */
console.log(str1.split(''));
/**
 * [
  'b', 'a', 'n',
  'a', ' ', ' ',
  'n', 'a'
]
 */
console.log(str2.split(''));

如果我们想避免字符的多个间距,我们可以在 split()join() 之间插入对 filter() 方法的调用。

function addSpace(str) {
  return str
    .split('')
    .filter((item) => item.trim())
    .join(' ');
}
// 字符串在某些字符之间有空格
const str1 = 'co  ffee';
const str2 = 'bana  na';
console.log(addSpace(str1)); // c o f f e e
console.log(addSpace(str2)); // b a n a n a

Array filter() 方法返回一个新数组,该数组仅包含原始数组中的元素,传递给 filter() 的测试回调函数为其返回真值。 对空格 (' ') 调用 trim() 会产生一个空字符串 (''),这在 JavaScript 中不是真值。 因此,从 filter() 返回的结果数组中排除了空格。

提示 ,在 JavaScript 中,只有六个假值:false、null、undefined、0、''(空字符串)和 NaN。 其他所有值都是真实的。


for…of 循环

对于更命令式的方法,我们可以使用 JavaScript for...of 循环在字符串的字符之间添加一个空格。

function addSpace(str) {
  // 创建一个变量来存储最终结果
  let result = '';
  for (const char of str) {
    // 在每次迭代中,将字符和空格添加到变量中
    result += char + ' ';
  }
  // 删除最后一个字符的空格
  return result.trimEnd();
}
const str1 = 'coffee';
const str2 = 'banana';
console.log(addSpace(str1)); // c o f f e e
console.log(addSpace(str2)); // b a n a n a

为了处理前面讨论的场景,其中字符串在某些字符之间有空格,请在每次迭代的字符上调用 trim(),并添加一个 if 检查以确保它是真实的,然后将它和空格添加到累积结果中:

function addSpace(str) {
  // 创建一个变量来存储最终结果
  let result = '';
  for (const char of str) {
    // 在每次迭代中,将字符和空格添加到变量。
    // 如果字符是空格,则将其修剪为空字符串,然后仅在为真时添加
    if (char.trim()) {
      result += char + ' ';
    }
  }
  // 删除最后一个字符的空格
  return result.trimEnd();
}
const str1 = 'co  ffee';
const str2 = 'bana  na';
console.log(addSpace(str1)); // c o f f e e
console.log(addSpace(str2)); // b a n a n a

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

JavaScript POST

发布时间:2024/03/23 浏览次数:96 分类:JavaScript

本教程讲解如何在不使用 JavaScript 表单的情况下发送 POST 数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便