[英]Replace parts of string with different string
我正在嘗試用不同的字符串替換字符串的一部分。 我有起始索引,結束索引和我試圖替換它的字符串。 這是數據的樣子:
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>
@[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: "" });
};
但問題是,一旦第一次提及被替換,其他提及變化的索引。 導致其他元素無法被替換。 有什么方法可以防止這種情況嗎?
我正在排序,因為在構造uidText
時mentions
的順序很重要。
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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.