I have a raw string like "fsfsdfsdd [qwewqewe] sdfsdfdf sdfsd[sdf]". How to get value from inside of [] this box and outside of [] this box. O/P fsfsdfsdd,sdfsdfdf,sdfsd & qwewqewe,sdf If it is possible to using JavaScript RegExp?
Asked
Active
Viewed 64 times
2 Answers
0
Try this solution:
str = "fsfsdfsdd [qwewqewe] sdfsdfdf sdfsd[sdf]";
s = str.match(/\[(\w+?)\]/g);
s.forEach(i => console.log(i));
Without square brackets:
res = Array.from(str.matchAll(/\[(.+?)\]/g));
res.forEach(i => console.log(i[1]));

An0ther0ne
- 324
- 3
- 8
-
It's showing only inside of the box values – vijay Dec 16 '19 at 09:41
-
@vijay, I added a solution to exclude square brackets. Enjoy it! – An0ther0ne Dec 16 '19 at 10:38
0
let str = "fsfsdfsdd [qwewqewe] sdfsdfdf sdfsd[sdf]";
let regex = /(?<=\[)(.*?)(?=\])/g;
let s1 = str.match(regex); // strings in the brackets
let s2 = str.replace(regex, '').replace(/[[]]/g, '').replace(/\s/, '').split(' '); // strings outside the brackets
let result = [...s1, ...s2]
console.log(result)

Addis
- 2,480
- 2
- 13
- 21