Divide by square bracket, even if there is no text inside the bracket

I had a problem splitting text using a square bracket in an array. If there is no text in the square bracket, then it will not catch. The code is in JavaScript, as shown below:

var text = 'This note is created on [date] by [admin;operator] for []'
var myArray = text.match(/\[([^[]+)\]/g);
console.log(myArray);

and result

["[date]", "[admin;operator]"]

but I want

["[date]", "[admin;operator]", []]

How to improve my template to get an empty square bracket ([])?

+4
source share
2 answers

Just replace +(1 or more) with *(0 or more)

var text = 'This note is created on [date] by [admin;operator] for []'
var myArray = text.match(/\[([^[]*)\]/g);
console.log(myArray);
Run codeHide result
+1
source

n+ Matches any string containing at least one n

n* Matches any string containing zero or more occurrences n

var text = 'This note is created on [date] by [admin;operator] for []'
var myArray = text.match(/\[([^[]*)\]/g);
console.log(myArray);
Run codeHide result
+1
source

Source: https://habr.com/ru/post/1693814/


All Articles