'regex to match all elements inside string

i want to get all strings between brackets []. i tried regex match methode and it's not working

i only get the first element changed

here is my code

tags = "[r,a,9]@[r,a,8].com".match(/([(?:[??[^[]*?]))/);
for (let index = 0; index < tagNumber; index++) {
  console.log(tags[index]);
  fromName = "[r,a,9]@[r,a,8].com".replace(tags[index], "haha");
}


Solution 1:[1]

/\[.+?\]/g

/ denotes the start of the pattern

\[ matches the [ character

.+? matches any character, 1 or more times, lazily

\] matches the ] character

/g denotes the end of the pattern and to find ALL matches

const input = "[r,a,9]@[r,a,8].com"
const pattern = /\[.+?\]/g

const tags = Array.from(input.match(pattern))
console.log(tags)

const fromName = input.replace(pattern, "haha")
console.log(fromName)

Solution 2:[2]

You need to escape [ and ] to match them literally. There's no need for the capture group around everything.

Add the g modifier to match all the occurrences in the string.

tags = "[r,a,9]@[r,a,8].com".match(/\[[^[]*?\]/g);
let tagNumber = tags.length;
for (let index = 0; index < tagNumber; index++) {
  console.log(tags[index]);
  fromName = "[r,a,9]@[r,a,8].com".replace(tags[index], "haha");
  console.log(fromName)
}

You can use a regular expression in replace() to replace all the matches at once.

fromName = "[r,a,9]@[r,a,8].com".replace(/\[[^[]*?\]/g, "haha");
console.log(fromName)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 cam
Solution 2 Barmar