Search code examples
javascriptstringreplacereplaceall

Using The .replaceAll() on a string literal array in Javascript


Goal: Use an array method to remove the strings get, right, the, first, time and replace them with the single string know in secretMessage array.

Plan Define a function to text in the rain, the old string, and the new string and use to .replaceall() methods and pass each one of the different arguments through one at a time, reassigning the array each call.

Code Thus Far

let secretMessage = ['Learning', 'is', 'not', 'about', 'what', 'you', 'get', 'easily', 'the', 'first', 'time,', 'it', 'is', 'about', 'what', 'you', 'can', 'figure', 'out.', '-2015,', 'Chris', 'Pine,', 'Learn', 'JavaScript'];
    

function replaceWords(orginalArray,oldString,updatedString){=
  let updatedArray= orginalArray.replaceAll(oldString,updatedString);//Not Sure If I need to wrap this in []
  return updatedArray;
}
secretMessage = replaceWords(secretMessage,'get','know');
secretMessage = replaceWords(secretMessage,'right','know');
secretMessage = replaceWords(secretMessage,'the','know');
secretMessage = replaceWords(secretMessage,'first','know');
secretMessage = replaceWords(secretMessage,'time','know');

console.log(secretMessage);

Current Results

let updatedArray= orginalArray.replaceAll(oldString,updatedString);
                               ^

TypeError:

orginalArray.replaceAll is not a function at replaceWords


Solution

  • Just for "fun", a solution using both an array method (Array.prototype.join()) and replaceAll() (String.prototype.replaceAll()) and close to your original idea, could be:

    function replaceWords(arr, oldStr, newStr) {
      return arr.join(' ')          // join all the array items into a single space-separated string
        .replaceAll(oldStr, newStr) // call `replaceAll()` on the newly created string
        .split(' ');                // split the string back into an array
    }
    
    let secretMessage = ['Learning', 'is', 'not', 'about', 'what', 'you', 'get', 'easily', 'the', 'first', 'time,', 'it', 'is', 'about', 'what', 'you', 'can', 'figure', 'out.', '-2015,', 'Chris', 'Pine,', 'Learn', 'JavaScript'];
    
    secretMessage = replaceWords(secretMessage, 'get', 'know');
    secretMessage = replaceWords(secretMessage, 'right', 'know');
    secretMessage = replaceWords(secretMessage, 'the', 'know');
    secretMessage = replaceWords(secretMessage, 'first', 'know');
    secretMessage = replaceWords(secretMessage, 'time', 'know');
    
    console.log(secretMessage);

    Having said that, I think nobody would do it in that way in real life ;)