Mary
Mary

Reputation: 157

Javascript find hashtags and replace based on certain condition

I need your help. I have a requirement to find hashtags and replace them based on certain conditions from an array of objects.

So this is the code:

texts: ["Your locale is #locale. You are from #country. Other name of your country is #others.",
 "Your locale is #locale. You are from #country. Other name of your country is #misc."
];

varsToChange: [{
  locale: "Chinese",
  country: "China",
  others: {
    name: "Republic of China",
  }
},{
  locale: "Japanese",
  country: "Japan",
  misc: {
    name: "Empire of Japan",
  }
}]

This is what I've tried:

textsToChange.replace(/(^|\W)(#[a-z\d][\w-]*)/ig, ' ' + ' '));

And obviously this is just changing all #hashtags occurrences. I can't figure out yet how to add the condition to match it from the vars array.

The output should be:

I'm fairly new to regex and would gladly appreciate any kind of help. Thanks in advance!

Upvotes: 0

Views: 49

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370779

You need to iterate through both arrays one-by-one, since the first text corresponds to the first varsToChange, and so on. So, use .map to transform each text into an element in a new array, and use its index parameter.

To dynamically determine what to replace a hashtag with, use a replacer function to look up the hashtag property on the current varsToChange object being iterated over:

const texts = ["Your locale is #locale. You are from #country. Other name of your country is #others.",
 "Your locale is #locale. You are from #country. Other name of your country is #misc."
];

const varsToChange = [{
  locale: "Chinese",
  country: "China",
  others: {
    name: "Republic of China",
  }
},{
  locale: "Japanese",
  country: "Japan",
  misc: {
    name: "Empire of Japan",
  }
}]

const result = texts.map(
  (text, i) => text.replace(
    /#(\w+)/g,
    (_, tag) => typeof varsToChange[i][tag] === 'string' ? varsToChange[i][tag] : varsToChange[i][tag].name
  )
);
console.log(result);

Upvotes: 2

Related Questions