簡體   English   中英

如何從與其他值聚合的jquery中的數組中刪除\\ n

[英]how to remove \n from an array in jquery aggregated with other values

我有一個像這樣的數組["\\n robort \\n \\ electronic","automated machine\\narm"];

我如何從該數組中刪除\\ n。 這樣我的結果看起來像

[" robort electronic","automated machine arm"]

我可以使用此代碼刪除單獨的(或分隔的)\\ n

 var arr = ["\\n", "\\n roborts\\n"]; var removeItem = '\\n'; arr = jQuery.grep(arr, function(value) { return value != removeItem; }); console.log(arr); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> 

您可以將其映射回去,並從每個索引中刪除換行符,並過濾掉所有只是換行符的內容

 var arr = ["\\n robort \\n \\ electronic","automated machine\\narm", "\\n"]; arr = arr.filter(function(item) { return item !== "\\n"; }).map(function(item) { return item.replace(/\\n/g,''); }); console.log(arr) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

沒有jQuery:

 var arr = ["\\n", "\\n roborts\\n"].map(function(val) { return val.replace(/\\n/g, ""); }); console.log(arr); 

這使用Array.prototype.map()返回一個包含現有數組各部分但刪除了換行符的數組。

用戶map()Link )數組和replace()函數。

var arr = ["\nautomated machine\narm", "\n roborts \n"];
var removeItem = /\n/g;

arr = arr.map( function(value) {
  return value.replace(removeItem, "");
});

console.log(arr);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM