2

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.

DesperateLearner
  • 1,115
  • 3
  • 19
  • 45
  • possible duplicate of [this question](http://stackoverflow.com/questions/7142890/remove-an-array-element-by-value-in-javascript) – James Westman Nov 29 '14 at 22:58
  • are you actually after `↵` or CR and LF? Also, do you want to remove the whole array element (containing that character) or just remove that character from the strings inside the array? – GitaarLAB Nov 29 '14 at 22:58
  • 1
    this is just one of the many arrays. Im not looking to remove that specific array alone. I did a string split to return an array. Its a string that hold that character, – DesperateLearner Nov 29 '14 at 23:00
  • Already figured you were doing that. Solution: then split the string on `/\s+/` and bob's your uncle `:)` – GitaarLAB Nov 29 '14 at 23:01

3 Answers3

0

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));
dfsq
  • 191,768
  • 25
  • 236
  • 258
0

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.

GitaarLAB
  • 14,536
  • 11
  • 60
  • 80
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;
}
StackSlave
  • 10,613
  • 2
  • 18
  • 35