I'm writing an autocomplete input in React Native using react-native-autocomplete-input. Everything is working so far, except if I input a special regex character for my input, like '(', I get an error 'Invalid regular expression: missing ) or '*', the error is 'Invalid regular expression, nothing to repeat.
I'm trying to match country names and some countries have parenthesis, but also if a user types a ? or *, I don't want the app to crash.
Here is the function that searches through an object of countries with names:
findCountry = (query) => {
if (query === '') {
return [];
}
const regex = new RegExp(`${query.trim()}`, 'i');
return countries.filter(country => country.name.search(regex) >= 0);
}
I think the error is somewhere in there. How do I set up the regex filter, so it ignores the special characters on input?
Here is the Autocomplete render function:
render() {
const { query } = this.state;
const countries = this.findCountry(query);
const comp = (a, b) => a.toLowerCase().trim() === b.toLowerCase().trim();
var { fetchingCountries, handleSearch } = this.props;
return (
<View style={styles.container}>
<Autocomplete
autoCapitalize="none"
autoCorrect={false}
containerStyle={styles.autocompleteInput}
data={countries.length === 1 && comp(query, countries[0].name) ? [] : countries}
defaultValue={query}
onChangeText={text => this.setState({ query: text })}
placeholder="Search for a Country or Territory"
renderItem={({ name }) => (
<TouchableOpacity onPress={() => this.setState({ query: name })}>
<Text style={styles.queryText}>
{name}
</Text>
</TouchableOpacity>
)}
/>
<TouchableOpacity
style={styles.searchButton}
onPress={() => handleSearch(query)}
>
{
fetchingCountries
? <ActivityIndicator size="small" color="white" />
: <Text style={styles.buttonText}>Search</Text>
}
</TouchableOpacity>
</View>
);
}
}