I'm trying to replace parts of a string with a different string. I have the starting index, ending index, and the string that I'm trying to replace it with. This is how the data looks like:
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?"
I was trying to replace the @[name] in text with the UID in this format: <@UID>.
So I came up with this:
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: "" });
};
But the problem is as soon as the first mention gets replaced the index of other mentions changes. Resulting in other elements not getting replaced. Is there any way to prevent this?
input.slice(start, end) == searchthen you can replace+ input.slice(start, end).replace(search, replace) +with just+ replace +.)mentions.sort((a, b) => b.startingIndex - a.startingIndex);to sort it in descending order.