0

есть строка text и массив ключевых слов this.state.keywords

необходимо произвести замену ключевых слов XXX в строке на выражения вида <span class = 'c0*'>XXX</span>

где * - значение от 1 до 4 (по сути номер ключевого слова в словаре по модулю 4)

Написал такой код:

highlightText = (text: string) => {
    let output: string = text;
    let index: number = 0;
    for (const keyword of this.state.keywords) {
        output = output.replace(new RegExp(keyword, 'ig'), `<span class='c0${index % 4 + 1}'>${keyword}</span>`, );
        index += 1;
    }

    return output;
}

Как по мне он корявенький и избыточный.

Подскажите, как бы его сделать поэлегантнее, условно можно ли его схлопнуть в пару строк

1 ответ 1

1

По короче - можно так.

const highlightText = (text) => {
    this.state.keywords.forEach((keyword, i) => {
        text = text.replace(new RegExp(keyword, "gi"), `<span class='c0${i % 4 + 1}'>${keyword}</span>`)
    })
    return text;
}

Удобнее для чтения - вот так:

const highlightText = (text) => {
    const keywords = this.state.keywords;

    keywords.forEach((keyword, i) => {
        const template =  `<span class='c0${i % 4 + 1}'>${keyword}</span>`
        const re = new RegExp(keyword, "gi");

        text = text.replace(re, template)
    })
    return text
}
1
  • кстати из ваш код натолкнул на такую идею: highlightText = (text: string) => this.state.keywords.reduce((res, keyword, i) => res = res.replace(new RegExp(keyword, "gi"), ``<span class = 'c0${i % 4 + 1}'>${keyword}</span>``), text);
    – Zhihar
    12 сен 2022 в 19:17

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.