user2343618
user2343618

Reputation: 163

Cannot manipulate array produced with string.match

I have produced an array using:

var arr = [];
arr = string.match(/(?:^| )([a-z]+)(?= [A-Z])/g);

This works as expected and the array is full and can be seen using console.log or alert().

The array consists of words which I need to filter, so I am trying to use .splice to remove unwanted instances of the same word using:

for (var i = arr.length - 1; i >= 0; i--) {
    if (arr[i] === 'jim') {
        arr.splice(i, 1);
    }
}

The for loop doesn't recognize any instances of, for instance, 'jim' in the array although there are several.

I tried the loop using an array I made myself and it worked fine, i.e.:

arr = ['jim', 'bob', 'arthur', 'jim', 'fred']

I have also tried the following which reports that 'jim' !== 'jim' as well as the other names not equalling 'jim'. Again this loop works fine with the self-assigned array.

var i = arr.length;
while ( i-- )
if (arr[i] === 'jim')
    arr.splice(i, 1);
else
    alert( "'" + arr[i].toString() + "' !== 'jim'" );

What is it about the array produced by the string.match that I am not understanding?

Upvotes: 1

Views: 65

Answers (2)

user3785863
user3785863

Reputation: 11

James is right: whitespace characters cause the problem here.

When I try your examples above the test alerts: ' jim' !== 'jim'. The first part/bracket of your regular expression includes a whitespace character in the matched strings.

The generated array will most likely be something like: arr = [' jim', ' bob', ' arthur', ' jim', ' fred'].

Upvotes: 0

Amit Joki
Amit Joki

Reputation: 59232

You can save a lot of time by using Array.filter():

arr = arr.filter(function(x){
   return x.trim() !== 'jim';   
});

Upvotes: 1

Related Questions