Javascript 用不同的字符串替换字符串的部分

Javascript 用不同的字符串替换字符串的部分,javascript,string,algorithm,replace,Javascript,String,Algorithm,Replace,我试图用不同的字符串替换字符串的部分。我有开始索引、结束索引和试图替换它的字符串。以下是数据的外观: 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?" 我试图

我试图用不同的字符串替换字符串的部分。我有开始索引、结束索引和试图替换它的字符串。以下是数据的外观:

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]:

所以我想到了这个:

  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时,提及的顺序很重要

const insertsinetions=文本,sinetions=>{ 常量比较器=提及1,提及2=> 提及1.startingIndex-提及2.startingIndex 常数减速机= [uidText,previousEndingIndex], {开始索引,结束索引,uid} => [ `${uidText}${text.substringpreviousEndingIndex,startingIndex}`, endingIndex ] 常量[uidText,previousEndingIndex]= 提及.sortcomparator.reducereducer,[,0] 返回uidText+text.substringpreviousEndingIndex } 常量提到=[ { uid:xyz, 启动指数:26, endingIndex:30, }, { 美国广播公司, 开始索引:0, endingIndex:9, 显示名称:John Doe, }, ] const text=@John Doe你好吗?嗨@Ben Sup?
console.loginsertsinetinstext,sineticsyou可以编写一个从字符串末尾开始的算法;这样,虽然长度仍然会改变,但前面提到的索引不会改变。如果input.slicestart,end==search,那么您可以将+input.slicestart,end.replacesearch,replace+替换为+replace+。@Tobsta谢谢!成功了。我只是在上面添加了这一行;按降序排序。@ArunKumar很高兴听到:-@AndrewMorton好的: