Reputation: 4067
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 ?
Upvotes: 0
Views: 330
Reputation: 785146
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]
)
Upvotes: 2