0

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));

2
  • 1
    Problem is somewhere else, your code works Commented May 21, 2015 at 7:40
  • @trigger I edited your question, care to hit "Run code snippet" and tell us what you see? Commented May 21, 2015 at 7:40

2 Answers 2

1

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

While I agree that this is better practise, the +1 method should actually work too.
indeed, indexOf('hello') returning -1 +1 means 0, which should be false, else it should evaluate to true, so this shouldn't be the problem, but it's surely a better practice :P
0

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);

2 Comments

Your issue is due to another piece of code, this one works perfectly.
Depends on what you mean by "invalid"! If it's corrupted you can't!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.