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.
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. 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.
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. (Older) Browsers that do not support trim()
can use:
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.
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;
}