[英]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. 您可以使用以下方法。
> 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'
>
> 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 (' '). 您的代码的唯一问题是
\\s
在replace
语句时也与\\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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.