1

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.

phuzi
  • 12,078
  • 3
  • 26
  • 50
user3348410
  • 2,733
  • 10
  • 51
  • 85
  • 1
    What have you tried and what issues did you encounter? Please provide a [minimal, complete, and verifiable example](https://stackoverflow.com/help/mcve). – Constantin Groß Oct 07 '19 at 09:34
  • Otherwise I'd assume this is a duplicate of https://stackoverflow.com/questions/2858121/how-to-convert-a-comma-separated-string-to-an-array – Constantin Groß Oct 07 '19 at 09:35
  • Could you explain the problem a little better? Put a more complete snippet of your code, and also what your code needs to do in order to function properly. – Alberto Perez Oct 07 '19 at 09:44

3 Answers3

1

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 })
Tarreq
  • 1,282
  • 9
  • 17
0

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]

Bad Dobby
  • 811
  • 2
  • 8
  • 22
0

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>
Fraction
  • 11,668
  • 5
  • 28
  • 48