gpt4 book ai didi

javascript - 用不同的字符串替换部分字符串

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:06:25 25 4
gpt4 key购买 nike

我正在尝试用不同的字符串替换字符串的一部分。我有起始索引、结束索引和要替换它的字符串。这是数据的样子:

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?"

我正在尝试替换 @[name] UID 格式的文本:<@UID> .

所以我想到了这个:

  replaceText = (input, search, replace, start, end) => {
return (
input.slice(0, start) +
input.slice(start, end).replace(search, replace) +
input.slice(end)
);
};

replaceWithMentions = () => {
const { sendMessage } = this.props;
const { mentions } = this.state;
let { text } = this.state;

text = mentions.reduce((text, mention) => {
return this.replaceText(
text,
`@${mention.displayName}`,
`<@${mention.uid}>`,
mention.startingIndex,
mention.endingIndex
);
}, text);

sendMessage(text);
this.setState({ text: "" });
};

但问题是,一旦第一个提及被替换,其他提及的索引就会发生变化。导致其他元素没有被替换。有什么办法可以避免这种情况吗?

最佳答案

这应该可以解决问题

我正在排序,因为 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))

关于javascript - 用不同的字符串替换部分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56751966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com