首页 > 解决方案 > Javascript根据特定条件查找主题标签并替换

问题描述

我需要你的帮助。我需要找到主题标签并根据对象数组中的某些条件替换它们。

所以这是代码:

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",
  }
}]

这是我尝试过的:

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

显然,这只是改变了所有#hashtags 事件。我还不知道如何添加条件以从 vars 数组中匹配它。

输出应该是:

我对正则表达式相当陌生,很乐意提供任何帮助。提前致谢!

标签: javascriptregex

解决方案


您需要一个接一个地遍历这两个数组,因为第一个文本对应于第一个varsToChange,依此类推。因此,使用.map将每个文本转换为新数组中的元素,并使用其索引参数。

要动态确定要替换主题标签的内容,请使用替换函数查找varsToChange正在迭代的当前对象的主题标签属性:

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);


推荐阅读