Creek Barbara
Creek Barbara

Reputation: 647

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. The code below should return (123,45,67,89) but instead it returns (1234567,89). The REGEX is the problem, probably, but I don't know how to fix it. 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);

Upvotes: 1

Views: 79

Answers (5)

hygull
hygull

Reputation: 8740

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 ]
>

Upvotes: 2

Aman Chhabra
Aman Chhabra

Reputation: 3894

The only issue with your code is that \s is matching \n as well while replace statement, so instead of \s use space (' ').

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);

Upvotes: 1

david
david

Reputation: 3218

Just change the regex pattern. First, remove all white space. After that, replace \n with ,.

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

Upvotes: 1

Akhil Aravind
Akhil Aravind

Reputation: 6130

I made it worked with your string, may be this is the hard way... everything has a plan 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(','));

Upvotes: 1

Zach Zeleznick
Zach Zeleznick

Reputation: 46

Try using the literal space ' ' instead of '\s' since

/\s/g any whitespace character

Check out regex101 the next time you get stuck -- it's really helpful!

Upvotes: -1

Related Questions