1

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.

6
  • If it works why bother changing it? Commented Jul 29, 2015 at 8:11
  • Why not loop through the array and use string.replace()? Commented Jul 29, 2015 at 8:11
  • @Andreas To futher my skills and to make the code more readable for other developers. (and my future self) Commented Jul 29, 2015 at 8:12
  • @stevenw00 like this: carpeDiem[i].replace('\n', '<br \>') Commented Jul 29, 2015 at 8:16
  • 1
    "...make the code more readable..." After reading it the first time I know exactly what the code is going to do. Fewer lines of code doesn't always mean better readability :) If you really want to change it, you could use .forEach() or, if you don't want to modify carpeDiem, .map() Commented Jul 29, 2015 at 8:19

2 Answers 2

2

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

1 Comment

why not just carpeDiem.map(function(i) { return i.replace('\n', '<br />'); });?
1

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

2 Comments

"The find() method returns a value in the array, if an element in the array satisfies the provided testing function." How is this supposed to satisfy the requirement - replace all strings "x" with string "y"?
So you're going to misuse .find() to replace the string passed as parameter s with "bar" if it matches "foo". This won't change the array! And even if it would change the value in the array it will only change the first occurance.

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.