javascript - 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 数组中匹配它。
输出应该是:
- 您的语言环境是中文。你来自中国。贵国的别称是中华民国。”
- 您的语言环境是日语。你来自日本。你们国家的另一个名字是日本帝国。”
我对正则表达式相当陌生,很乐意提供任何帮助。提前致谢!
解决方案
您需要一个接一个地遍历这两个数组,因为第一个文本对应于第一个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);
推荐阅读
- security - 可以在我的网站中覆盖 applicationhost.config 中 http 动词的 RequestFiltering 值吗?
- visual-studio - Matlab:无法加载文件或程序集
- html - 悬停时菜单在导航栏中向左移动
- lorawan - 无法使 AT Master 应用程序在 NUCLEO-LRWAN1/NUCLEO-L073RZ 对上工作
- android - 我正在尝试调用 DisplayMatch 给 listviewMatch.setAdapter(adapter) 中的错误,如果可能的话,请帮助我提供任何替代方案
- reactjs - 如何在材质 UI 按钮组件上传递数据
- angular - 子组件引用父组件时出现 Angular NG3003 错误
- node.js - 使用 supertest 模拟每个测试依赖项
- python - 使用 Python 将单波段 Tif 图像转换为伪彩色单波段图像
- javascript - 按对象字段对数组进行排序