How to count the number of vowels, consonants, and characters in a string using react native?

Viewed 291

i want to count the number of consonants/vowels/characters depending on the user's given word, then the result is displayed on the screen. I have tried to solve however it still didn't show up

export default class App extends Component{
  constructor(){
    super();
      this.state ={
        value: '',
        consonant: 0,
        vowels: 0,
        characters:0,
      }
  }

  WordAnalyzer = () => {
    this.setState({value: this.state.value}),
    () => {

      const listVowel=['a','i','u','e','o','A','I','U','E','O'];
      let arr_word= this.state.value.split('');
      for (let j=0; j<arr_word.length; j++){
        for (let i=0; i< listVowel.length; i++){
          if (arr_word[j] == listVowel[i]){
            this.setState({vowels: this.state.vowels + 1});
          }
          else{
            this.setState({consonant: this.state.consonant +1});
          }
        }
        this.setState({characters: this.state.characters +1});
      }
    };
  }


  render(){
    return(
      <View style={styles.container}>
        <Text style={styles.header}>Word Analyzer</Text>
        <TextInput style= {styles.input} onChangeText={(value) =>this.setState({value})} placeholder='Input a word here' />
        <Button color = '#841584' onPress={this.WordAnalyzer} title='Analyze'/>
        <Text>Word            :   {this.state.value}</Text>
        <Text>No of Consonants:   {this.state.consonant}</Text>
        <Text>No of Vowels    :   {this.state.vowels}</Text>
        <Text>No of Characters:   {this.state.characters}</Text>
      </View>     
    );
  }
}

1 Answers

It'd be alot less work (for both you and your computer) if you were to simply use match on the string to figure out how many vowels and consonants are in it.

And, of course, you can simply use this.state.value.length to get the number of characters.

Thus, WordAnalyzer can be refactored into the much simpler:

    WordAnalyzer = () => {
        const vowelsCount = this.state.value.match(/[AaEeIiOoUu]/g).length;
        this.setState({
            characters: this.state.value.length,
            vowels: vowelsCount,
            consonant: this.state.value.match(/[a-zA-z]/g).length - vowelsCount
        });
    };

Related