Home > Blockchain >  How to split a string into array based on []?
How to split a string into array based on []?

Time:02-18

I am trying to split a string into an array of words that is present within []. Consider I have a string stating =>

const savedString = '[@hello] [@Bye], [@Friends] will miss you.'

Now I want to break the string into an array that will only contain.

const requiredArray = ['hello', 'Bye', 'Friends'];

I know about the split(), but only one delimiter can be passed. Need help.

https://www.w3schools.com/jsref/jsref_split.asp

CodePudding user response:

You can achieve this with regex.

const savedString = '[@hello] [@Bye], [@Friends] will miss you.';
const regex = /\[@([a-zA-Z] )\]/g;
const matches = savedString.match(regex);
const result = matches.map(match => match.replace(/\[@|\]/g, ''));
console.log(result);

CodePudding user response:

You can use .match() method with a regular expression with lookahead and lookbehind:

const savedString = '[@hello] [@Bye], [@Friends] will miss you.'

const n = savedString.match(/(?<=\[@)[^\]]*(?=\])/g);

console.log( n );

  • Related