user3348410
user3348410

Reputation: 2833

How to separate string and push to react state?

I worried if I copy and paste like this string to input:

10202, 29292, 29111, 29222, 22822, 

How can I delete spaces and commas or any character except numbers and push it to react component state?

my state will be like:

codes: [10202, 29292, 29111, 29222]

On copy paste I know I can use onPaste method, but don't know how get each item delete commas and push state of course there need to be prevenet duplicate same values.

Upvotes: 1

Views: 876

Answers (3)

Fraction
Fraction

Reputation: 12954

Try this example:

function App() {
    const [codes, setCodes] = React.useState();
    
    function inputPaste(ev) {
      const str = ev.clipboardData.getData('Text');
      const input = str.split(', ').filter(Number);
      setCodes(input);     
    } 

    return(<div>
      <span>Copy/Paste this <pre>10202, 29292, 29111, 29222, 22822, </pre></span><br/>
      <input type="text" onPaste={inputPaste} />
      <br/><br/>
      <span>codes: {JSON.stringify(codes)}</span>
    </div>);
}

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.10.2/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.10.2/umd/react-dom.production.min.js"></script>
    <div id="root"></div>

Upvotes: 0

Bad Dobby
Bad Dobby

Reputation: 871

try

input.split(',').map(item => item.trim()).filter(Boolean).map(Number)

example:

function getArrayOfNumbers(input) {
  return input
    .split(',')
    .map(item => item.trim())
    .filter(Boolean)
    .map(Number)
}

getArrayOfNumbers('1234, 5678,  45889')
// returns [1234, 5678, 45889]

getArrayOfNumbers('0, 123 , 3.14159  , 0.15, 0.0  ')
// returns [0, 123, 3.14159, 0.15, 0]

Upvotes: 0

Tarreq
Tarreq

Reputation: 1365

You can do something like:

const data = '10202, 29292,  29111,29222,22822,   '

const codes = data.split(',')
                     .map(item => (item.trim()))  // remove any spaces
                       .filter(item => item !== '')  // exclude any empty values caused by extra comma at end
                         .map(item => parseInt(item))  // parse to Int

// if you wanna see data in log
console.log(codes)

this.setState({ codes })

Upvotes: 1

Related Questions