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 );
What of [@hello hell[@Bye bye]
=> Bye bye
If say for example the string is: '[@hello] [@Bye], [@Friends] will miss you [@hello hell[@Bye bye].'
One approach would be add to the above solution map()
so each element is .split()
at [@
and call pop()
on the resulting array:
//starting with [ "hello", "Bye", "Friends", "hello hell[@Bye bye" ]
.map(word =>
//split word into array
word.split('[@')
//[ ["hello"], ["Bye"], ["Friends"], ["hello hell", "Bye bye"] ]
//Now take the last element
.pop()
)
//Result: [ "hello", "Bye", "Friends", "Bye bye" ]
DEMO
const savedString = '[@hello] [@Bye], [@Friends] will miss you [@hello hell[@Bye bye].';
const n = savedString.match(/(?<=\[@)[^\]]*(?=\])/g).map(w => w.split('[@').pop());
console.log( n );
Note:
Just so that you do not run into errors whenever there's no match, consider changing:
savedString.match(/(?<=\[@)[^\]]*(?=\])/g)`
To:
(savedString.match(/(?<=\[@)[^\]]*(?=\])/g) || [])