简体   繁体   English

在Javascript中按任意3个选项(换行符,逗号,空格)分割字符串

[英]Split string by any 3 options (newline, comma, white space) in Javascript

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. 可以从csv字符串,由空格分隔的字符串或由换行符分隔的字符串中复制/粘贴此字符串。 So ideally I'd be able to handle all 3 (or more separators in the future). 理想情况下,我将能够处理所有3个(或更多的分隔符)。

Currently I have the below code but I just get an array of empty strings when I copy/paste from all 3 scenarios: 目前我有以下代码,但是当我从所有3个场景中复制/粘贴时,我只得到一个空字符串数组:

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

It seems to be the \\S+ that causes the issue. 似乎是导致问题的\\ S +。 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. 如果我只有\\ n,它适用于/ n和逗号,但只要我添加\\ S +它就会为所有内容提供所有空字符串。

\\s+ not \\S+ and get rid of whitespace after a comma \\s+不是\\S+并在逗号后删除空白

 var str = `1,2,3,4,5, 6, 7 8 9 10` console.log(str.replace(/,\\s+/g,",").split(/[\\n,\\s+]/)) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM