Home > Software engineering >  Replacing multiple parts of a string with params passed into method
Replacing multiple parts of a string with params passed into method

Time:10-14

I have a function called translate that looks something like this:

export const translate = (sentence: string, ...words) => { ... }

It looks into the settings to see what language is selected and then looks up the translated sentences dictionary.

Here is an example sentence: "Each __ provides __ money".

After translating the sentence into the correct language, I want to check to see if there are any __ in the string. That is what the param ...words is for. We would then replace the __ using the param words

Example of me using the function: translate('Each __ provides __ money', 'Person', 'Fifty') would return: Each Person provides Fifty moneybut translated.

Im currently having a problem with how to go about replacing the __.

I was thinking about doing something with .split:

if (sentence.includes('__')) {
  let rebuiltSentence = ''
  const splitSentence = sentence.split('__')
  
  for (let i = 0; i < splitSentence.length; i  ) {
    const part = splitSentence[i]
    rebuiltSentence  = part
    rebuiltSentence  = words[i]
  }

  return rebuiltSentence
}

But this seems a bit hacky to me. Is there any way I can maybe get the index of each __ then replace it with the correct word index in the words param?

CodePudding user response:

You could use String#replace with a regex pattern and a callback that iterates the words array:

const translate = (sentence, ...words) => {
  let i = 0;
  return sentence.replace(/\b__\b/g, () => words[i  ]);
};

console.log(translate("Each __ provides __ money", "Person", "Fifty"));

If it should handle the situation when there aren't enough words to fit the blanks:

const translate = (sentence, ...words) => {
  let i = 0;
  return sentence.replace(/\b__\b/g, m =>
    i < words.length ? words[i  ] : m
  );
};

console.log(translate("Each __ provides __ money", "Person"));

Or using split, a bit closer to the spirit of your original approach:

const translate = (sentence, ...words) =>
  sentence
    .split(/\b__\b/g)
    .map((e, i) => i === 0 ? e : (words[i-1] || "__")   e)
    .join("")
;

console.log(translate("Each __ provides __ money", "Person", "Fifty"));

  • Related