简体   繁体   English

Javascript / Regex:Split()在我的情况下不起作用

[英]Javascript/Regex: Split() not working for my case

My split() is not working when there is a space before or after each line in my variable. 当变量中的每一行之前或之后都有空格时,split()不起作用。 The code below should return (123,45,67,89) but instead it returns (1234567,89). 下面的代码应返回(123,45,67,89),但应返回(1234567,89)。 The REGEX is the problem, probably, but I don't know how to fix it. REGEX可能是问题所在,但我不知道如何解决。 Your help will be appreciated. 您的帮助将不胜感激。 Thank you, 谢谢,

  var keywordsArray = "1 2 3 \\n4 5\\n 6 7\\n8 9"; keywordsArray = keywordsArray.replace(/\\s\\s+/g,' ').split('\\n'); alert(keywordsArray); 

You can use the below approaches. 您可以使用以下方法。

Sepearted with , (comma): 以,(逗号)分隔:

> var result = keywordsArray.split('\n')
undefined
> result
[ '1 2 3  ', '4 5', ' 6       7', '8 9' ]
>
> result = result.map(s => s.replace(/\s+/g, ''))
[ '123', '45', '67', '89' ]
>
> result.join(',')
'123,45,67,89'
>

Array of integers: 整数数组:

> var keywordsArray = "1 2 3  \n4 5\n 6       7\n8 9"
undefined
> keywordsArray
'1 2 3  \n4 5\n 6       7\n8 9'
>
> var result = keywordsArray.split('\n')
undefined
> result
[ '1 2 3  ', '4 5', ' 6       7', '8 9' ]
>
> result = result.map(s => parseInt(s.replace(/\s+/g, '')))
[ 123, 45, 67, 89 ]
>

I made it worked with your string, may be this is the hard way... everything has a plan B 我让它与您的琴弦配合使用,可能是这很困难...一切都有计划B

 var keywordsArray = "1 2 3 \\n4 5\\n 6 7\\n8 9"; keywordsArray = keywordsArray.split('\\n').map(item => item.replace(/\\s/g,'')); console.log(keywordsArray.join(',')); 

Just change the regex pattern. 只需更改正则表达式模式即可。 First, remove all white space. 首先,删除所有空白。 After that, replace \\n with , . 在此之后,替换\\n,

var keywordsArray = "1 2 3  \n4 5\n 6       7\n8 9";
keywordsArray = keywordsArray.replace(/ */g,'').replace(/\n/g,',');
console.log(keywordsArray);

For more information about regex, check this link 有关正则表达式的更多信息,请检查此链接

The only issue with your code is that \\s is matching \\n as well while replace statement, so instead of \\s use space (' '). 您的代码的唯一问题是\\sreplace语句时也与\\n匹配,因此请不要使用\\s\\s ')。

Please find your code with just update mentioned above: 请通过上面提到的更新找到您的代码:

 var keywordsArray = "1 2 3 \\n4 5\\n 6 7\\n8 9"; keywordsArray = keywordsArray.replace(/ +/g,' ').split('\\n'); alert(keywordsArray); 

Try using the literal space ' ' instead of '\\s' since 尝试使用文字空间''代替'\\ s',因为

/\\s/g any whitespace character / \\ s / g任何空格字符

Check out regex101 the next time you get stuck -- it's really helpful! 下次遇到问题时 ,请查看regex101-这真的很有帮助!

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

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