0

var s = "Hello, how are you?";
var r = /([,\s?]+)/;
console.log(s.split(r));

Why do i get an empty string at the end of the array?

4
  • What are you trying to do? Commented Jul 3, 2018 at 7:38
  • Your expression matches a single ?. If you use /([,\s]+)/ instead, you'll get "you?" as the last element. If you don't want that either, manually remove the last element. Commented Jul 3, 2018 at 7:40
  • Because you're splitting on the last character. Commented Jul 3, 2018 at 7:40
  • Is there a way to prevent this from happening or do i always have to check the string's last character and only then split it? Commented Jul 3, 2018 at 9:55

2 Answers 2

2

Remove the question mark after the \s.

var s = "Hello, how are you?";
var r = /([,\s]+)/;
console.log(s.split(r));

Sign up to request clarification or add additional context in comments.

Comments

1

Because you ar splitting on the question mark too. Without it:

var s = "Hello, how are you?";
var r = /([,\s]+)/;
console.log(s.split(r));
// including question mark in the split
// and empty values removed from the result
console.log(s.split(/([,\s]+|[?])/).filter(v => v.length));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.