Displaying First and Last Characters with Ellipsis in React Native: ✨ abc…xyz ✨
When working with strings, particularly number or string, it’s often necessary to truncate the middle portion for better readability. This blog post will guide you through creating a JavaScript function that displays the first and last characters of a string with an ellipsis in between.
1. Create a Component
Here’s the complete code :
import React from 'react';
import { Text } from 'react-native';
const Ellipsis = ({num}:any) => {
if (num.length < 14) {
return <Text>{token}</Text>;
} const firstPart = num.slice(0, 6);
const lastPart = num.slice(-6);
const displayedToken = `${firstPart}...${lastPart}`; return <Text>{displayedToken}</Text>;
};export default Ellipsis;
2. Props Handling: The component receives a num
as a prop.
import React from 'react';
import { SafeAreaView, StyleSheet } from 'react-native';
import Ellipsis from './components/Ellipsis';
const App = () => {
const exampleNum = '1234567890abcdef123456';
return (
<SafeAreaView style={styles.container}>
<Ellipsis num={exampleNum} />
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});
export default App;
This simple component is highly reusable and can be easily integrated into any React Native application where you need to display truncated num. It’s an excellent example of how React Native allows developers to build clean and efficient UI components.