Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

To replace a string in react native, just use the replace() method for replacing the first occurrence and replaceAll() for replacing all occurrences.

Like the following example, we can replace a string with any string or empty ( blank ).

"Hello Infinitbility".replace("Hello", "Hi"); // 'Hi Infinitbility'
"Hello Infinitbility".replaceAll("i", "-"); // 'Hello Inf-n-tb-l-ty'

Today, I’m going to show you How do i replace strings in react native based on their occurrence, as above mentioned here, I’m going to use the replace() and replaceAll() method for replacing strings.

Let’s start today’s tutorial how do you replace a string in react native?

In this example, we will replace a string in a text component ( in a render method ).

Let’s write code…

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

export default function App() {
    const [string, setString] = useState("Hello Infinitbility");

    return (
        <View style={styles.container}>
            <Text>{string.replace("Hello", "Hi")}</Text>
            <Text>{string.replaceAll("i", "-")}</Text>
        </View>
    );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

As mentioned above, we are taken the example of a replace string, use the replace() and replaceAll() method in react native render, and printed it on the screen.

Let’s check the output.

React Native, replace string example
React Native, replace string example

Try it yourself

I hope it’s help you, All the best 👍.