fix(InputMenu/SelectMenu): escape regexp before search

Resolves nuxt/ui#2308
This commit is contained in:
Benjamin Canac
2024-10-10 16:12:42 +02:00
parent dd0d0551be
commit c68ba76fd0
2 changed files with 16 additions and 4 deletions

View File

@@ -401,20 +401,26 @@ export default defineComponent({
lazy: props.searchLazy lazy: props.searchLazy
}) })
function escapeRegExp (string: string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}
const filteredOptions = computed(() => { const filteredOptions = computed(() => {
if (!query.value || debouncedSearch) { if (!query.value || debouncedSearch) {
return options.value return options.value
} }
const escapedQuery = escapeRegExp(query.value)
return options.value.filter((option: any) => { return options.value.filter((option: any) => {
return (props.searchAttributes?.length ? props.searchAttributes : [props.optionAttribute]).some((searchAttribute: any) => { return (props.searchAttributes?.length ? props.searchAttributes : [props.optionAttribute]).some((searchAttribute: any) => {
if (['string', 'number'].includes(typeof option)) { if (['string', 'number'].includes(typeof option)) {
return String(option).search(new RegExp(query.value, 'i')) !== -1 return String(option).search(new RegExp(escapedQuery, 'i')) !== -1
} }
const child = get(option, searchAttribute) const child = get(option, searchAttribute)
return child !== null && child !== undefined && String(child).search(new RegExp(query.value, 'i')) !== -1 return child !== null && child !== undefined && String(child).search(new RegExp(escapedQuery, 'i')) !== -1
}) })
}) })
}) })

View File

@@ -485,20 +485,26 @@ export default defineComponent({
lazy: props.searchableLazy lazy: props.searchableLazy
}) })
function escapeRegExp (string: string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}
const filteredOptions = computed(() => { const filteredOptions = computed(() => {
if (!query.value || debouncedSearch) { if (!query.value || debouncedSearch) {
return options.value return options.value
} }
const escapedQuery = escapeRegExp(query.value)
return options.value.filter((option: any) => { return options.value.filter((option: any) => {
return (props.searchAttributes?.length ? props.searchAttributes : [props.optionAttribute]).some((searchAttribute: any) => { return (props.searchAttributes?.length ? props.searchAttributes : [props.optionAttribute]).some((searchAttribute: any) => {
if (['string', 'number'].includes(typeof option)) { if (['string', 'number'].includes(typeof option)) {
return String(option).search(new RegExp(query.value, 'i')) !== -1 return String(option).search(new RegExp(escapedQuery, 'i')) !== -1
} }
const child = get(option, searchAttribute) const child = get(option, searchAttribute)
return child !== null && child !== undefined && String(child).search(new RegExp(query.value, 'i')) !== -1 return child !== null && child !== undefined && String(child).search(new RegExp(escapedQuery, 'i')) !== -1
}) })
}) })
}) })