javascript - 如何在文本中获取自定义标签,并放入另一个文本?
问题描述
标题问题可能不容易理解。希望您能在下面了解我的详细信息。
我在下面有句子数据,有一些标签,由[tn]tag[/tn]
:
const sentence = `[t1]Sometimes[/t1] that's [t2]just the way[/t2] it has to be. Sure, there
were [t3]probably[/t3] other options, but he didn't let them [t4]enter his mind[/t4]. It
was done and that was that. It was just the way [t5]it[/t5] had to be.`
我有句子的一部分。
const parts = [
"Sometimes that's just the way",
"it has to be",
"Sure,",
"there were probably other options,",
"but he didn't let them enter his mind.",
"It was done and that was that.",
"It was just the way it had to be."
];
目标是使用上面的句子在每个部分上添加标签。
const expectedOutput = [
"[t1]Sometimes[/t1] that's [t2]just the way[/t2]",
"it has to be",
"Sure,",
"there were [t3]probably[/t3] other options,",
"but he didn't let them [t4]enter his mind[/t4].",
"It was done and that was that.",
"It was just the way [t5]it[/t5] had to be."
];
到目前为止,我尝试过以下内容,但似乎没有任何意义,而且我什么也没做。
- 做一个克隆句子,并删除所有标签。(下面的代码)
- 找出句子中的所有部分。
- [问题是我不知道如何重新放置标签]
我想问有没有机会实现它?如何。谢谢
export const removeTags = (content) => {
content = content.replace(/([t]|[\/t])/g, '');
return content.replace(/([t\d+]|[\/t\d+])/g, '');
};
解决方案
对于正则表达式答案:/\[t\d+\]([^[]*)\[\/t\d+\]/g
将匹配包括标签在内的所有单词,然后对这些标签中的所有单词进行分组。
let regex = /\[t\d+\]([^[]*)\[\/t\d+\]/g;
let matches = [], tags = [];
var match = regex.exec(sentence);
while (match != null) {
tags.push(match[0]);
matches.push(match[1]);
match = regex.exec(sentence);
}
现在我们只需要将 all 替换matches
为tags
inside ofparts
let lastSeen = 0;
for (let i = 0; i < parts.length; i++) {
for (let j = lastSeen; j < matches.length; j++) {
if (parts[i].includes(matches[j])) {
lastSeen++;
parts[i] = parts[i].replaceAll(matches[j], tags[j])
} else if (j > lastSeen) {
break;
}
}
}
这是查看正则表达式的链接:regex101
这是一个 JSFiddle 可以看到整个JSFiddle
推荐阅读
- node.js - 如何终止路由中间件链?
- android - 读取通话记录条目 - 号码、名称和持续时间,即使有 READ_CALLLOG 也被 Play 商店拒绝,拨号器权限
- windows - Ansible 无法使用 UNC Choco 源安装 Chocolatey 包
- excel - 如何在vba中停止滚动条自动跳转
- c - pthread_exit 中参数的目的是什么?
- sql-server - 使用编辑时数据库更新失败
- watson-knowledge-catalog - 向 Watson Knowledge Catalog 中的资产添加其他元数据
- ruby-on-rails - ABCService.new.do_foo - 为什么不是类方法?
- c++ - 如何使 CLion 自动格式化具有 Google 代码风格的 C++ 代码,并通过 google cpplint 检查
- powershell - 提供 scriptblock 选项时,Start-Parallel 模块未执行功能块