[英]Removing return carriage from an array - Javascript
I have array as shown below: 我有如下所示的数组:
["↵", "Oh", "yeah,", "did", "we", "mention", "it’s", "free?↵"]
Is there a way I can remove that ↵ from the string and from the array? 有没有一种方法可以从字符串和数组中删除该??
I tried 我试过了
str.replace(/(\r\n|\n|\r)/gm,"");
This didn't help. 这没有帮助。
You can clean up your array from empty strings using String.prototype.trim
combined with Array.prototype.filter
to remove falsy values. 您可以将
String.prototype.trim
与Array.prototype.filter
结合使用以清除虚假值,从而从空字符串中清除数组。 For example: 例如:
var arr = ["\\n", "", "Oh", "yeah,", "did", "we", "mention", "it's", "free?\\n"] // check array before alert(JSON.stringify(arr)); arr = arr.map(function(el) { return el.trim(); }).filter(Boolean); // after cleaning up alert(JSON.stringify(arr));
Simply split your string on /\\s+/
, then you don't need to perform this action anymore. 只需在
/\\s+/
上分割字符串,就不再需要执行此操作。
var str='\nOh yeah, did we mention it’s free?\n';
var arr=str.split(/\s+/);
Note: you might want to trim \\s+
from the beginning and end of the string fist. 注意:您可能需要从字符串拳头的开始和结尾处修剪
\\s+
。 (Older) Browsers that do not support trim()
can use: (较早的)不支持
trim()
)的浏览器可以使用:
arr=str.replace(/^\s+|\s+$/g, '').split(/\s+/);
Strictly answering your question how to remove 'carriage returns' from strings in an array: 严格回答您的问题,如何从数组中的字符串中删除“回车符”:
// you have:
var str= '\nOh yeah, did we mention it’s free?\n';
var arr= str.split(' ');
// no function needed, a simple loop will suffice:
for(var L=arr.length; L--; arr[L]=arr[L].replace(/[\n\r]/g, ''));
Note that (as can already be seen in your example as array-item 0) you might end up with some empty strings (not undefined) in your array. 请注意(在您的示例中已经以array-item 0看到),您可能最终在数组中添加了一些空字符串(不是未定义)。
Try this: 尝试这个:
function removeReturn(ary){
var b = [], a = [];
for(var i=0,l=ary.length; i<l; i++){
var s = ary[i].split('');
for(var n=0,c=s.length; n<c; n++){
if(s[n] === '\u021B5')s[n] = '';
}
b.push(s.join(''));
}
for(var i=0,l=b.length; i<l; i++){
var x = b[i];
if(x !== '')a.push(x);
}
return a;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.