Home > Back-end >  how to extract an array from a string in javascript
how to extract an array from a string in javascript

Time:02-28

i have a string which contains array in it and bracket , i want to extract data from it .

    let vr = "- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API."

how can i dynamically identify if an array is present in this string , like take [Next.js Documentation] since it is an array. Please help me on this issue

CodePudding user response:

You can use regex with javascript's String.prototype.match().

The regex pattern to match anything enclosed by brackets is /\[(.*?)\]/gm. You can check here.

Good luck!

CodePudding user response:

let vr = "- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API."
const regex = /\[([^\]] )\]\(([^)] )\)/g;
let match;
let result = [];
while ((match = regex.exec(vr)) !== null) {
  result.push(match[1]);
}
console.log(result);

CodePudding user response:

let vr = "- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API."

const re = /\[([^]*?)]/g;
let match = re.exec(vr);
if (match !== null) {
    console.log(match[1]);
} else {
    // not matched
}
  • Related