首页 > 解决方案 > 如何在文本中获取自定义标签,并放入另一个文本?

问题描述

标题问题可能不容易理解。希望您能在下面了解我的详细信息。

我在下面有句子数据,有一些标签,由[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."
];

到目前为止,我尝试过以下内容,但似乎没有任何意义,而且我什么也没做。

  1. 做一个克隆句子,并删除所有标签。(下面的代码)
  2. 找出句子中的所有部分。
  3. [问题是我不知道如何重新放置标签]

我想问有没有机会实现它?如何。谢谢


export const removeTags = (content) => {
  content = content.replace(/([t]|[\/t])/g, '');
  return content.replace(/([t\d+]|[\/t\d+])/g, '');
};

标签: javascriptregex

解决方案


对于正则表达式答案:/\[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 替换matchestagsinside 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


推荐阅读