我正在尝试用其他字符串替换字符串的一部分。我有开始索引,结束索引以及要替换的字符串。数据如下所示:
const mentions = [{ uid: "abc", startingIndex: 0, endingIndex: 9, displayName: "John Doe" }, { uid: "xyz", startingIndex: 26, endingIndex: 30}];
let text = "@John Doe How are you? Hi @Ben Sup?"
我试图用以下格式的UID替换文本中的@[name]
。
所以我想到了这个:
<@UID>
但是问题是,第一次提及的索引被替换后,其他提及的索引就会改变。导致其他元素无法替换。有什么办法可以防止这种情况?
答案 0 :(得分:0)
我正在进行排序是因为mentions
的顺序在构造uidText
时很重要。
const insertMentions = (text, mentions) => {
const comparator = (mention1, mention2) =>
mention1.startingIndex - mention2.startingIndex
const reducer = (
[uidText, previousEndingIndex],
{startingIndex, endingIndex, uid}
) => [
`${uidText}${text.substring(previousEndingIndex, startingIndex)}<@${uid}>`,
endingIndex
]
const [uidText, previousEndingIndex] =
mentions.sort(comparator).reduce(reducer, ["", 0])
return uidText + text.substring(previousEndingIndex)
}
const mentions = [
{
uid: "xyz",
startingIndex: 26,
endingIndex: 30,
},
{
uid: "abc",
startingIndex: 0,
endingIndex: 9,
displayName: "John Doe",
},
]
const text = "@John Doe How are you? Hi @Ben Sup?"
console.log(insertMentions(text, mentions))