Заменить части строки другой строкой - PullRequest
0 голосов
/ 25 июня 2019

Я пытаюсь заменить части строки другой строкой.У меня есть начальный индекс, конечный индекс и строка, которую я пытаюсь заменить.Вот как выглядят данные:

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>.

Итак, я придумал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: "" });
  };

Но проблема в том, что, как только первое упоминание будет заменено, индекс других упомянутых изменений.В результате чего другие элементы не заменяются.Есть ли способ предотвратить это?

1 Ответ

0 голосов
/ 26 июня 2019

Это должно сработать

Я сортирую, потому что порядок 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))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...