how to much words in a text and surround them with span?

Viewed 39

I have a map in javascript that includes some keys with their values.

I have also a sentence that can include some words that can be as keys in the map.

I want to add the span tag for these words and add the titre attribute for each span where the value for this attribute is the corresponding value in the map.

I have this code:

const html = $('#fake_textarea').val().replace(
    /\p{L}+/gu, // Match every word respecting Unicode letters
    word => {
        const wordLowercased = word.toLowerCase();

        if (!map.has(wordLowercased)) {
            return word;
        }

        return $('<span>')
            .text(word)
            .attr('title', map.get(wordLowercased))
            .css({
                color: 'red',
                fontWeight: 'bold',
            })
            .prop('outerHTML');
    }
);

this code works well for keys consisting of one word. But if a key consiting of two words then the will not be able to surround it with a span.

how can update the code to achieve that?

0 Answers
Related