gpt4 book ai didi

javascript - jQuery 去掉数组中的空格

转载 作者:行者123 更新时间:2023-11-30 08:01:02 29 4
gpt4 key购买 nike

我正在尝试从我的数组内容中去除所有空格。

这是我的数组

var array = ["option 1", "option 2", "option 3"]

我尝试使用此处找到的答案:how do I strip white space when grabbing text with jQuery?

这就是我正在尝试使用的 jQuery。

$(array1).each(function(entry) {
$(this).replace(/\s+/g, '');
console.log(entry);
});

但它抛出一个 TypeError: undefined is not a function (evaluating 'entry.replace(/\s+/g, '')')

我错过了什么?

最佳答案

您可以使用 map 来创建一个新数组。

在 map 函数中,您对值使用正则表达式。


jQuery

array = $.map(array, function(value){
return value.replace(/ /g, '');
});

Fiddle ;


普通 JS 版本

array = array.map(function(value){
return value.replace(/ /g, '');
});

Fiddle


旧的 IE Vanilla JS

for(var i=0; i<array.length; i++){
array[i] = array[i].replace(/ /g, '');
};

Fiddle


无循环通用方法(可能与字符有冲突)

array = array.join('$').replace(/ /g, '').split('$');

Fiddle

关于javascript - jQuery 去掉数组中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28354197/

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