Digvijay
Digvijay

Reputation: 3271

How to get substring in React Native

I am fetching data from Api and showing it in FlatList but I want to show only limited string to the user not the whole text I am getting from the Api.

Below is the sample text I am getting from server.

 "Text": "Apu Nahasapeemapetilon - Apu Nahasapeemapetilon is a recurring character in the American animated television series The Simpsons." 

Here I want to show data only till - after - I don't want this long data to show in Flatlist.Is there any way to get text only before - sign.

Below is my code:

import React, {useEffect,useState} from 'react';
import {View,Text,StyleSheet,ActivityIndicator,FlatList} from 'react-native';

const List = () => {

const[post,setPost] = useState([]);
const[isLoading,setLoading] = useState(true);

useEffect(() => {
    
    const url = 'http://api.duckduckgo.com/?q=simpsons+characters&format=json';
    fetch(url).then((res) => res.json())
    .then((resp) => setPost(resp.RelatedTopics))
    .catch((err) => alert(err));
 },[]);

    return(

      <View>

            <FlatList 
            data = {post} 
            keyExtractor = {(item) => item.FirstURL} 
            renderItem = {({item}) => <Text>{item.Text}</Text>} />
      
      </View>
    );

};

const styles = StyleSheet.create({
 testStyle:{
     flex: 1,
     justifyContent:"center",
     alignItems:"center"
   }
});

export default List; 

Someone let me know how can I get desired result.

Upvotes: 0

Views: 153

Answers (1)

Pramod
Pramod

Reputation: 1940

When showing the text node in flatlist use slice method

eg var a = "Apu Nahasapeemapetilon - Apu Nahasapeemapetilon is a recurring character in the American animated television series The Simpsons."

then

a.split('-', 1)[0] will give "Apu Nahasapeemapetilon "

Upvotes: 2

Related Questions