0

I have a textbox that the users can copy/paste string data into. This is going to be a string of numbers. This string of numbers could be copied/pasted from a csv string, a string separated by space, or separated by newline. So ideally I'd be able to handle all 3 (or more separators in the future).

Currently I have the below code but I just get an array of empty strings when I copy/paste from all 3 scenarios:

var data = event.originalEvent.clipboardData.getData('text/plain').split(/[\n,\S+]/);

It seems to be the \S+ that causes the issue. If I just have \n, it works for both /n and commas but as soon as I add the \S+ it gives all empty strings for everything.

  • Possible duplicate of [How do I split a string with multiple separators in javascript?](https://stackoverflow.com/questions/650022/how-do-i-split-a-string-with-multiple-separators-in-javascript) – Easwar Jun 11 '19 at 14:57
  • 1
    `\s+`, not `\S+` : `console.log(\`1,2,3,4,5,6 7 8 9 10\`.split(/[\n,\s+]/))` – mplungjan Jun 11 '19 at 14:58
  • _This question was caused by a problem that can no longer be reproduced or a simple typographical error. While similar questions may be on-topic here, this one was resolved in a manner unlikely to help future readers. This can often be avoided by identifying and closely inspecting the shortest program necessary to reproduce the problem before posting._ – mplungjan Jun 11 '19 at 15:00
  • @mplungjan So what's interesting with that is if the commas have a space after them like "25, 64, 57" I end up with elements in the array that is empty strings. Same thing happens with the /n copy/paste from excel. After each number I get 2 empty string elements in the array. – user11545716 Jun 11 '19 at 15:03
  • Please see my adjusted answer – mplungjan Jun 12 '19 at 06:02

1 Answers1

1

\s+ not \S+ and get rid of whitespace after a comma

var str = `1,2,3,4,5, 6, 7
8 9 10`

console.log(str.replace(/,\s+/g,",").split(/[\n,\s+]/))
mplungjan
  • 169,008
  • 28
  • 173
  • 236