jQuery从数组中删除空格

jQuery strip spaces out of array

本文关键字:删除 空格 数组 jQuery      更新时间:2023-09-26

我正试图从数组的内容中去掉所有空格。

这是我的阵列

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

我试着使用这里的答案:使用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函数中,您可以对您的值使用regexp。


jQuery

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

小提琴


Vanilla JS版本

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

Fiddle


旧IE香草JS

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

Fiddle


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

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

Fiddle

这里不需要使用jQuery,只需使用普通数组方法,如map或simple-for-loop:

var array1 = ["option 1", "option 2", "option 3"].map(function(el) {
    return el.replace(/'s*/g, '')
});
document.write(array1);

这个简单的for循环遍历数组项,并删除不需要jQuery或正则表达式的任何空格。

var arr = ["option 1", "option 2", "option 3"];
for (var i = 0; i < arr.length; i++) {
    alert(arr[i].replace(' ', ''));
}

看看"each"在jQuery中是如何工作的,它并不是你想象的那样。可以通过注意回调的第一个参数是数组的索引来修复此代码,因此可以像这样调整代码

var array1 = ["option 1", "option 2", "option 3"]
$(array1).each(function(entry, value) {
  array1[entry] = value.replace(/'s+/g, '');
  console.log(array1[entry]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

$(this)不是你想要的,你想要的是entry,这是你的字符串

entry = entry.replace(/'s+/g, '');

实际上,你的字符串是第二个参数。所以你需要将你的功能更改为function(key, entry),也就是

这就是为什么它不起作用,但我建议在这里使用一些其他解决方案。$.each不是最好的选择,你想map