我试图从数组的内容中删除所有空格.
这是我的阵列
var array = ["option 1", "option 2", "option 3"]
Run Code Online (Sandbox Code Playgroud)
我尝试使用这里找到的答案:如何在使用jQuery抓取文本时剥离空格?
这就是我正在尝试使用的jQuery.
$(array1).each(function(entry) {
$(this).replace(/\s+/g, '');
console.log(entry);
});
Run Code Online (Sandbox Code Playgroud)
但它抛出了一个 TypeError: undefined is not a function (evaluating 'entry.replace(/\s+/g, '')')
我错过了什么?
您可以使用map创建一个新数组.
在map函数中,您可以在值上使用正则表达式.
array = $.map(array, function(value){
return value.replace(/ /g, '');
});
Run Code Online (Sandbox Code Playgroud)
小提琴 ;
array = array.map(function(value){
return value.replace(/ /g, '');
});
Run Code Online (Sandbox Code Playgroud)
for(var i=0; i<array.length; i++){
array[i] = array[i].replace(/ /g, '');
};
Run Code Online (Sandbox Code Playgroud)
array = array.join('$').replace(/ /g, '').split('$');
Run Code Online (Sandbox Code Playgroud)