Reputation: 38
I'm struggling with a regex.
I am able to split the string at the required location, but when it is added to an array, the array has an empty string at the start.
// This is the string I am wanting to split.
// I want the first 4 words to be separated from the remainder of the string
const chatMessage = "This is a string that I want to split";
// I am using this regex
const r = /(^(?:\S+\s+\n?){4})/;
const chatMessageArr = chatMessage.split(r);
console.log(chatMessageArr);
It returns:
[ '', 'This is a string ', 'that I want to split' ]
But need it to return:
[ 'This is a string ', 'that I want to split' ]
Upvotes: 0
Views: 45
Reputation: 780909
Add a second capture group to the regexp and use .match()
instead of .split()
.
// This is the string I am wanting to split.
// I want the first 4 words to be separated from the remainder of the string
const chatMessage = "This is a string that I want to split";
// I am using this regex
const r = /(^(?:\S+\s+\n?){4})(.*)/;
const chatMessageArr = chatMessage.match(r);
chatMessageArr.shift(); // remove the full match
console.log(chatMessageArr);
Upvotes: 0
Reputation: 521178
I wouldn't use string split here, I would use a regex replacement:
var chatMessage = "This is a string that I want to split";
var first = chatMessage.replace(/^\s*(\S+(?:\s+\S+){3}).*$/, "$1");
var last = chatMessage.replace(/^\s*\S+(?:\s+\S+){3}\s+(.*$)/, "$1");
console.log(chatMessage);
console.log(first);
console.log(last);
Upvotes: 1