Himmators
Himmators

Reputation: 15006

Replace instance of item in array?

I have an array with strings if the string is foo I wish to replace it with bar.

I could do a for-loop:

for (var i = carpeDiem.length - 1; i >= 0; i--) {
    if(carpeDiem[i] === '\n'){
        carpeDiem[i] = '<br \>'
    }
};

But is there a nicer way to do it. I only need to support modern browsers.

Upvotes: 1

Views: 63

Answers (2)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123377

You could use Array.map(), e.g. http://codepen.io/anon/pen/QbJqeq

var carpeDiem = ['\n', '<br />', '\n', '<br />'];

carpeDiem = carpeDiem.map(function(i) { 
    return i.replace('\n', '<br />') 
});

console.log(carpeDiem) // ['<br />', '<br />', '<br />', '<br />'];

Upvotes: 2

Zibellino
Zibellino

Reputation: 1433

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

This is the thing for you, it's ES6 so should work at least in FF, but there are polyfills for it (that are probably doing the same as your code above).

Upvotes: 1

Related Questions