trigger
trigger

Reputation: 497

Trouble with text replace in array Javascript (Angular)

I need to remove 'hello' substring from each object field in objects array. And i have an error "Cannot read property 'indexOf' of null". It happens, because i try to change object field in loop. But What to do? :) I use AngularJS.

var array = [
    {text: 'hello user1'},
    {text: 'hello user2'},
    {text: 'user3'},
    {text: 'hello user4'},
];
for (i = 0; i < array.length; i++) {
    if (array[i].text.indexOf('hello') + 1) {
        array[i].text = array[i].text.replace('hello','');
    }
}

// For demo
document.write(JSON.stringify(array));

Upvotes: 0

Views: 193

Answers (2)

Satpal
Satpal

Reputation: 133403

Your condition condition is not correct.

The indexOf() method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex. Returns -1 if the value is not found

change your condition to

if(array[i].text.indexOf('hello') > -1){
    //Rest of your code
}

Upvotes: 1

SharpEdge
SharpEdge

Reputation: 1762

Change + to > -1

indexOf() returns the index of the string searched, in case it's not found returns -1.

if indexOf > -1 it means that there is some hello word in the string

var array = [
	{text: 'hello user1'},
	{text: 'hello user2'},
	{text: 'user3'},
	{text: 'hello user4'},
];
for (i = 0; i < array.length; i++) {
  if (array[i].text.indexOf('hello') > -1) {
    array[i].text = array[i].text.replace('hello','');
  }
}
    
console.log(array);

Upvotes: 0

Related Questions