'How to split a string into array based on []?
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 hello] [@Bye bye], [@Friends forever] will miss you.'
Now I want to break the string into an array that will only contain.
const requiredArray = ['hello hello', 'Bye bye', 'Friends forever'];
I know about the split(), but only one delimiter can be passed. Need help.
Solution 1:[1]
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) || [])
Solution 2:[2]
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);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Parvesh Kumar |
