0

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' ]
1
  • What have you tried so far to solve this on your own? .slice(), a different regex, ... Commented Mar 24, 2021 at 15:46

2 Answers 2

1

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

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

2 Comments

So would you suggest the below to place the now two separate strings into one array? chatMessageArr.push(chatMessage.replace(/^\s*(\S+(?:\s+\S+){3}).*$/, "$1")); chatMessageArr.push(chatMessage.replace(/^\s*\S+(?:\s+\S+){3}\s+(.*$)/, "$1"));
Yes, you could do that. There might also be some canonical way to split a string in JavaScript on a single nth occurrence of some pattern. This might be a better alternative to the answer I gave you above.
0

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

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.