0

I have a problem. I try to convert my string dynamically, but for some reason, it only converts the first letter of my initial string. What can I do to solve this?

Ex:

input: Mike
String_1 = 'Mike'
String_2 = 13 (I want it to be 139115, 13 for M, 9 for I, 11 for k and 5 for e).

This is my code:

import './App.css';
import React, {useState} from 'react';
import emojies from './emojies';

function App() { 

  let [String_1, setString_1] = useState( '' );
  let [String_2, setString_2] = useState( '' );
  let [Index, setIndex] = useState();
  return (
    <div>
      <div>
        <input
          type="text"
          value={String_1}
          placeholder="Enter a message"
          onChange={e =>  {
                    const val = e.target.value;
                    setString_1(val);
                    setString_2(val.toLowerCase().charCodeAt(0)-96);
                      }
        }
    />

  </div>


  <div>
    <p>{String_1}</p>
    <p>{String_2}</p>
  </div>
</div>
  );
}

export default App;
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129

3 Answers3

1

This has nothing to do with React or setState.

Your issue is the logic around generating that String_2.

As you can see from the below snippet, your val.toLowerCase().charCodeAt(0)-96 only returns 13, so setState is acting correctly by passing on that value.

const val = 'Mike'

const String_2 = val.toLowerCase().charCodeAt(0) - 96
console.log(String_2)

const correct = parseInt(val.toLowerCase().split('').map(x => x.charCodeAt() - 96).join(''))
console.log(correct)

The new logic splits the string up into chars, maps over each of them to create a list of chars, then joins them together and converts into a int.

Luke Storry
  • 6,032
  • 1
  • 9
  • 22
0

You make a mistake on setting the value for String_2.

Try this.

setString_2(val.split("").map(c => {
       return c.toLowerCase().charCodeAt(0) - 96; 
   }).join(""));
do thuan
  • 459
  • 3
  • 11
0

Pass your string value from input box to this function. It iterates over all the alphabets from the string and convert them to their idx + 1 and join everything.

const convertStringToCharIdxString = (str) => {
    const calcCharIdx = (char) => char.charCodeAt(0) - 97 + 1; // + 1, because you are considering a as 1
    return str.split('').map(calcCharIdx).join('');
}