mike10101
mike10101

Reputation: 23

how to remove the spaces in an Array?

i am trying to create a program that stores words in an Array, what I've done is whatever the program finds a separator (" " or ",") it pushes it in the array, my problem here is that it store even the separators with it (i must use the array SEPARATORS).

var sentence = prompt("");

var tab = [];

var word = "" ;

var separators = [" ", ","];

for(var i = 0 ; i< sentence.length ; i++){

    for(var j = 0 ; j < separators.length ; j++){

    if(sentence.charAt(i) != separators[j] && j == separators.length-1){

           word += sentence.charAt(i); 

        }else if(sentence.charAt(i) == separators[j]){

           tab.push(word);
           word = "";

        }

    }

}

tab.push(word);
console.log(tab);

Upvotes: 1

Views: 243

Answers (3)

Patrick Gunderson
Patrick Gunderson

Reputation: 3281

After reexamining the problem, I think you need a combination of native string functions and the compact method from the excellent underscore library which removes 'falsy' entries in an array:

$('#textfield).keyup(analyzeString);
var words;
function analyzeString(event){
    words = [];
    var string = $('#textfield).val()
    //replace commas with spaces
    string = string.split(',').join(' ');
    //split the string on spaces 
    words = string.split(' ');
    //remove the empty blocks using underscore compact
    _.compact(words);
}

Upvotes: 0

Minko Gechev
Minko Gechev

Reputation: 25682

You can try this:

var text = 'Some test sentence, and a long sentence';
var words = text.split(/,|\s/);

If you don't want empty strings:

var words = text.split(/,|\s/).filter(function (e) {
    return e.length;
});
console.log(words); //["some", "test", "sentence", "and", "a", "long", "sentence"]

If you need to use the array you can try this:

var text = 'Some test sentence, and a long sentence',
    s = [',', ' '],
    r = RegExp('[' + s.join('') + ']+'),
    words = text.split(r);

Upvotes: 3

Blender
Blender

Reputation: 298166

I would just use regex:

var words = sentence.split(/[, ]+/);

If you want to fix your code, use indexOf instead of a for loop:

for (var i = 0; i < sentence.length; i++) {
    if (separators.indexOf(sentence.charAt(i)) === -1) {
        word += sentence.charAt(i);
    } else {
        tab.push(word);
        word = "";
    }
}

Upvotes: 2

Related Questions