How to replace arabic numerals with English in TextInput in React Native

I have a Email text field which allows entering Arabic numbers. On entering arabic number, I want to change them to English but it is getting duplicated when I enter second or third arabic number for eg. when I type - test٢٣@gmail.com . I will provide the code I used to replace arabic number. What can I do to stop duplication.

const Test = () => {
  const [state, setState] = useState('');
  // Convert arabic numerals in string to English.
  const a2e = s => s.replace(/[٠-٩]/g, d => '٠١٢٣٤٥٦٧٨٩'.indexOf(d));

  return (
    <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
      <TextInput style={{ borderWidth: 1, color: "black" }}
        ref={inputRef}
        placeholder='Please enter Email'
        value={state}
        keyboardType="email-address"
        onChangeText={(changedText) => {
            // Replace arabic number with English number in the string.
            let filteredMail= a2e(changedText);
            setState(filteredMail);
          }
        }

      />
    </View>
  )
}

Upvotes: 0

Views: 872

Answers (1)

wassim AJ
wassim AJ

Reputation: 458

This worked for me, I directly called the a2e function inside the setState.

PS: I removed the "ref={inputRef}" as the inputRef is not declared in the Test component.

const Test = () => {
  const [state, setState] = useState('');
  // Convert arabic numerals in string to English.
  const a2e = s => s.replace(/[٠-٩]/g, d => '٠١٢٣٤٥٦٧٨٩'.indexOf(d));

  return (
    <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
      <TextInput style={{ borderWidth: 1, color: "black" }}
        placeholder='Please enter Email'
        value={state}
        keyboardType="email-address"
        onChangeText={value => {
            setState(a2e(value));
          }
        }

      />
    </View>
  )
}

Upvotes: 2

Related Questions