Home > other >  Assign numbers to alphabets in react js
Assign numbers to alphabets in react js

Time:05-02

  • Firstly, i wanna assign numbers to all alphabets like this:a=1,b=2,c=3,d=4 etc.

  • Secondly, I want to create an input field and submit Button.

  • Thirdly, when I enter alphabets on that input field, (eg: abcd it shows 1234 because i already mentioned above, a=1, b=2, c=3, d=4).

  • And last, I wanna to add them (eg: I entered "abcd" and output is 1234 and add them.)Final Output for abcd is 1 2 3 4 =10.

    import React,{useState} from 'react' import "../node_modules/bootstrap/dist/css/bootstrap.min.css"

const Data = () => { const [data, setData] = useState({a: 1,b: 2,c: 3,d: 4,e: 5,f: 6,g: 7,h: 8,i: 9,j: 10,k: 11,l: 12,m: 13,n: 14,o: 15,p: 16,q: 17,r: 18,s: 19,t: 20,u: 21,v: 22,w: 23,x: 24,y: 25,z: 26})

const changeHandler = e => {
    setData({...data,[e.target.name]:[e.target.value]})
   
   
}
const submitHandler=e=> {
    e.preventDefault();
    
  }
return (
<div>
    <form onSubmit={submitHandler}>
    <input type="text"onChange={changeHandler}/><br/>
    <button className="btn btn-primary"onClick={()=>setData(console.log(data))}>Click</button><br/>
    </form>


</div>

) }

export default Data

CodePudding user response:

Presented below is one possible way to achieve the desired objective.

Code Snippet

const {useState} = React;

const Thingy = ({...props}) => {
  // state variable to hold user input
  const [userInput, setUserInput] = useState('');
  
  // state variable to track user submit button click
  const [showResult, setShowResult] = useState(false);
  
  // method to update "userInput" state variable
  const handleChange = ev => (setUserInput(ev.target.value), setShowResult(false));
  
  // method to conver a single character (a to z) into number (1 to 26)
  const convertChar = ch => {
    const c = ch.toLowerCase();
    // if user input is a digit, ensure return value is a "string"
    if ('0' <= c && c <= '9') return ch.toString();
    if (!('a' <= c && c <= 'z')) return ch;         // do not convert non-alpha
    return c.charCodeAt(0) - 'a'.charCodeAt(0)   1;
  };
  
  // method to transform user-input into numbers
  const transformInput = () => userInput
    .split('')                    // split the string into array of individual letters
    .map(c => convertChar(c))     // use the "convertChar" method
    .join(' ');                   // join back to string with "space" seperator
                        // added a "space" only for rendering to UI

  // method to find the sum/total of numbers
  const getResult = () => userInput
    .split('')                  // convert string to array of individual letters
    .map(c => convertChar(c))   // transform a-z to numbers 1-26
    .filter(                    // discard any characters except a-z, A-Z
      c => (
        typeof c !== 'string' &&    // check letter is no longer "string"
        !isNaN(c)                   // and it is not "NaN"
      )
    )
    .reduce(                    // add the numbers using ".reduce()"
      (total, itm) => total   itm, 0
    );
  
  // return the JSX that will be rendered on the UI
  // ----
  // description of elements
  // ^^^^^^^^^^^ ^^ ^^^^^^^^
  // 1. label - "enter text" to prefix the input-box
  // 2. input - to obtain the user input
  // 3. "<p>" - paragraph elt to show a-z transformed to 1-26
  // 4. button - submit button to calculate the sum
  // 5. "<p>" - paragraphe elt to show the result of the summation
  // -----
  // NOTE: Items 4, 6 and conditionally rendered
  return (
    <div>
      <div>
        <label htmlFor={'usrinp'}>Enter text: </label>
        <input
          id="usrinp"
          value={userInput}
          onChange={handleChange}
        />
      </div>
      {
        userInput.length > 0 &&
        <p>Converted text to: {transformInput()}</p>
      }
      <button onClick={() => setShowResult(true)}>
        Submit
      </button>
      {
        showResult && <p>Result is: {getResult()}</p>
      }
    </div>
  );
};

ReactDOM.render(
  <div>
    <h4>Transform User input text to numbers</h4>
    <Thingy />
  </div>,
  document.getElementById("rd")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="rd" />

Explanation

Inline comments added to the snippet above.

CodePudding user response:

you can do something like this

const dictionary = Object.fromEntries(Array(26).fill('a').map((s, i) => [String.fromCharCode(s.charCodeAt()   i), i   1]))


export default function App() {
  
  const [string, setString] = useState('')
  const [numbers, setNumbers] = useState([])

  const changeHandler = (e) => {
    setString(e.target.value)
  }

  useEffect(() => {
      setNumbers(
        string.toLowerCase().split('').map(c => dictionary[c])
      )
  }, [string])

  const calculateTotal = () => {
    console.log(numbers.reduce((a, b) => a   b))
  }
  
  
  return (
    <div className="App">
    <div>{numbers.join(' ')}</div>
    <input type="text" onChange={changeHandler} value={string}/><br/>
    <button className="btn btn-primary"onClick={calculateTotal}>Click</button><br/>
    
    </div>
  );
}

  • Related