1

I have the following string:

group:[random text]_updated_at

and I'm trying to extract the text inside the brackets []. Basically I want to print out this text:

random text

I've tried using split function

let arr = str.split('[')[1];

console.log(arr); // random text]_updated_at

but I believe it could better using regex? Does anyone know how I can print the text using regex?

NOTE:

  1. I don't want to use substring because the text within the brackets could potentially change.
  2. The text group: will always be there in the beginning.
Devmix
  • 1,599
  • 5
  • 36
  • 73
  • 1
    Have a look at this community wiki [Reference - What does this regex mean?](https://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean) which explains common regex tasks (which this is) and also links to an answer which provides a regex for [text in between curly brackets](https://stackoverflow.com/questions/413071/regex-to-get-string-between-curly-braces/413077#413077) which you should easily be able to adjust to work for square brackets. – Mushroomator Aug 30 '23 at 20:54

1 Answers1

1

I think match function might be right fit for the job. For example, check the code below:

let str = "group:[random text]_updated_at";
let match = str.match(/group:\[(.*?)\]/);
if (match) {
  console.log(match[1]); // Output: "random text"
}
Harshit Saini
  • 368
  • 1
  • 3
  • 10
  • str.match(/group:\[(.*?)\]_(\w+)/) should work in case if updated_at is needed to be kept. match[1] + " " + match[2] could be used to calculate the final output. – Harshit Saini Aug 30 '23 at 21:54