Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

192
Views
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");
}

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

/\[.+?\]/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)

about 4 years ago · Juan Pablo Isaza Report

0

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)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!