Home > Mobile >  How to replace all occurrences of a string with strings from an array
How to replace all occurrences of a string with strings from an array

Time:11-21

I have a string that contains "..." in different places. And a string array with the same amount of words as the number of "...".

I want to replace all occurrences of "..." with the words from the string array.

let stringToReplace = "I want an ... that I get from the ..."
let stringArray = ["apple","shop"]

result = "I want an apple that I get from the shop"

I have tried this:

let result = stringToReplace;
for (let i = 0; i < stringArray.length; i  ) {
   let inloc = stringArray[i];
   result = result.replace("...", inloc);
}

But that would only change the first occurrence of "...".

CodePudding user response:

let s = "I want an ... that I get from the ..."
let r = ["apple","shop"]

console.log(s.split('...').flatMap((e,i)=>[e,r[i]]).join(''));

CodePudding user response:

Do you want something like this?

//  stringToReplace = "I want an ... that I get from the ..."
//  stringArray = ["apple","shop"]

// result = "I want an apple that I get from the shop"

function replaceString(stringToReplace, stringArray) {
  var result = stringToReplace;
  for (var i = 0; i < stringArray.length; i  ) {
    result = result.replace("...", stringArray[i]);
  }
  return result;
}

console.log(
  replaceString("I want an ... that I get from the ...", ["apple", "shop"])
);

CodePudding user response:

This seems like a good use case for JS Reduce

let stringToReplace = "I want an ... that I get from the ..."
let stringArray = ["apple","shop"]

const PLACEHOLDER = '...'

const replaceWords = (stringWithPlaceholders, variablesArray) => {
  const finalString = stringWithPlaceholders.split(PLACEHOLDER).reduce((acc, curr, i) => {
      const variableToAdd = variablesArray[i]
      const newStringSection = variableToAdd ? `${acc}${curr}${variableToAdd}` : `${acc}${curr}`
      
      return newStringSection
    }, '')

  return finalString
}

console.log(replaceWords(stringToReplace, stringArray))

// => 'I want an apple that I get from the shop'

You might want to add in some default replacement in the case that you don't have the right amount of elements in your variables array, but this should help as a starting point.

  • Related