Filipe Costa
Filipe Costa

Reputation: 23

prepend and append a tag at each occurence of a string

Basically I have a simple search feature where you can search anything, my problem at the moment is that I need to highlight the searched word on all my articles. For example if I search "Spain" and I have a article like with the following title: "Spain is the best country, on Spain we have..." I need to highlight both "Spain" words.

I already made some attempts & currently I have a function below where my entry.title is the article title, "Spain is the best country, on Spain we have..." and the search Word is "Spain", this solves my problem but just with 1 occurrence.

    processTitle () {
        let newTitle = this.entry.title
        if(this.entry.title.includes(this.searchWord) && this.searchWord) {
            newTitle = this.entry.title.split(this.searchWord)
            console.log(newTitle)
            return `${newTitle[0]} <b>${this.entry.title}</b> ${newTitle[1]}`
        }

        return newTitle
    },

I Need to have a fresh new title where I have all occurrences of the searched word highlighted. Any help with this?

Upvotes: 0

Views: 43

Answers (1)

Krzysztof Krzeszewski
Krzysztof Krzeszewski

Reputation: 6714

You can use regex to search entire string globally for all occurences of the phrase and replace it with a new one

const title = "Spain is the best country, on Spain we have...";
const searchWord = "Spain";

function replaceAll(title, searchWord) {
    const replacement = `<b>${searchWord}</b>`
    return title.replace(new RegExp(searchWord, 'g'), replacement);
};

console.log(replaceAll(title, searchWord));

Upvotes: 1

Related Questions