Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replacing multiple parts of a string with params passed into method

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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"));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading