gpt4 book ai didi

javascript - 如何从数组Javascript中的最后一个元素中删除空格

转载 作者:行者123 更新时间:2023-12-03 00:41:33 25 4
gpt4 key购买 nike

所以我想知道如何删除数组中最后一个元素的空间。

假设我有一个字符串:

  let str = "d d, b b, c c, d d ";
let split = str.split(", ");
let arr = split.map(str => str.replace(/\s/g, '_'));
console.log(arr);

正如你所看到的,我在数组内链接单词,但我有一个问题,数组中的最后一个项目末尾有空格,最后以“_”结尾。我如何从最后一个元素中删除该空格而不删除 d d 之间的空格?

最佳答案

您可以使用String.prototype.trim() .

The trim() method removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).

let str = "d d, b b, c c, d d ";
let split = str.trim().split(", ");
let arr = split.map(str => str.replace(/\s/g, '_'));
console.log(arr);

关于javascript - 如何从数组Javascript中的最后一个元素中删除空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53443352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com