Saturday, 4 December 2021

Vue: Make matching part of input bold, including special hyphens

I have made a simple select component in Vue with a search/filter system. Based on the user input I'm showing some Belgium city suggestions.

Working example: https://codesandbox.io/s/wandering-lake-lecok?file=/src/components/Select.vue (Sometimes there is an error message in Codesandbox. Refresh the build in browser and it should work)

I want to take the UX one step further and show the matching part of the user input bold and underlined. Therefore I have a working makeBold function. By splitting the suggestion string into multiple parts I can add a bold and underline tag and return the suggestion.

computed: {
    results() {
        return this.options.filter((option) =>
        option.display_name
            .replaceAll("-'", "")
            .toLowerCase()
            .includes(this.searchInput.replaceAll("-'", "").toLowerCase())
        );
    },
},
methods: {
    makeBold(str, query) {
        const n = str.toUpperCase();
        const q = query.toUpperCase();
        const x = n.indexOf(q);

        if (!q || x === -1) {
            return str;
        }

        const l = q.length;

        return (
            str.substr(0, x) + "<b><u>" + str.substr(x, l) + "</u></b>" + str.substr(x + l)
        );
    },
}

One problem, a lot of cities in Belgium use dashes and/or apostrophes. In the suggestions function I'm removing this characters so a user doesn't need to type them. But in the makeBold function I would like to make this characters bold and underlined.

For example:

When the input is 'sint j', 'sintj' or 'Sint-j' I want the suggestions to look like 'Sint-Jans-Molenbeek' and 'Sint-Job in't Goor'

Is there someone who can give me a breakdown on how to achieve this?



from Vue: Make matching part of input bold, including special hyphens

No comments:

Post a Comment