Home > Net >  NodeJS match with regex gets last word than after space
NodeJS match with regex gets last word than after space

Time:02-03

var prefix = '.'
var str = '.kick blah 1 2 3'.match(`${prefix}kick (.*) (.*)`);

console.log(str)

result: [ 'blah 1 2', '3', index: 0, input: '.kick blah 1 2 3', ]

I wanted result to be [ 'blah', '1 2 3', index: 0, input: '.kick blah 1 2 3', ]

CodePudding user response:

You need to make the first group non-greedy, or else "." will keep matching..

Change the regex to ${prefix}kick (.*?) (.*)

CodePudding user response:

You can modify the regular expression pattern to include (.*) after ${prefix}kick, which matches any characters between .kick and the following two capture groups:

var prefix = '.';
var str = '.kick blah 1 2 3'.match(new RegExp(`${prefix}kick (.*) (.*) (.*)`));
console.log(str);

this will be the output

['.kick blah 1 2 3', 'blah', '1 2', '3', index: 0, input: '.kick blah 1 2 3']

So, the desired result is in str[1] and str[2] ' ' str[3].

  • Related