How do I use .replace() in arrays? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How do I use .replace() in arrays?

var myArray = ["blue dog", "red dog", "yellow dog"]; Now from myArray, I want to replace every "dog" to "cat". How do I do that?

9th Mar 2020, 11:18 PM
Ginfio
Ginfio - avatar
2 Answers
+ 5
var out = myArray.map( a => a.replace("dog","cat") );
9th Mar 2020, 11:24 PM
Calviղ
Calviղ - avatar
+ 3
replace is String.prototype.replace() You have to call with an instance of string. if you are not familiar with Array ES6 method forEach, use traditional for loop to loop through the array of strings. replace also takes its second argument in function form.
10th Mar 2020, 12:43 AM
Gordon
Gordon - avatar