0

This is for the use case of input line which is rather short (on purpose). It supposed to autosend message when the input is full but keep last word in place.

I am looking for regex that would fulfill these scenarios:

input: "testing"
output: [1] - "testing"; [2] - null

input: "testing testing"
output: [1] - "testing"; [2] - "testing"

input: "testing testing testing"
output: [1] - "testing testing"; [2] - "testing"

input: "testing testing testing "
output: [1] - "testing testing"; [2] - "testing "

So far I came up with these variants:

/(.*)\s+(\w+)/ - closest solution, but doesn't match for one word without spaces
/(.*)(?:\s+(\w+))?/ - is not recognizing last word

I am not sure how to fulfill all scenarios. Is it even possible ?

3
  • str.split(/\b/).pop() ? Commented Jul 16, 2014 at 10:25
  • See this stackoverflow.com/questions/17069122/… Commented Jul 16, 2014 at 10:26
  • @adeneo I didn't wanted split because I would have to join again. Seems like waste of resources. Commented Jul 16, 2014 at 10:46

1 Answer 1

2

You can use this String#match:

var input = 'testing1 testing2 testing3 ';
var m = input.match(/^(.+?)(?: +(\w+\ *))?$/);
// ["testing1 testing2 testing3 ", "testing1", "testing2 testing3 "]

And use group #2 and group #3 in the resulting array. (using m[1] and m[2])

Online Regex Demo

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

1 Comment

That looks really great, thanks ! I will give it a try in real app.

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.