Why do nested parentheses cause blank lines in this regex?

Why do nested parentheses cause blank lines in this regex?

var str = "ab((cd))ef"; var arr = str.split(/([\)\(])/); console.log(arr); // ["ab", "(", "", "(", "cd", ")", "", ")", "ef"] 

what i want to achieve is

 ["ab", "(", "(", "cd", ")", ")", "ef"] 
+6
source share
2 answers

The external parameters in your regular expression act as a capture group. From the split documentation ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split ):

If the delimiter is a regular expression that contains a parenthesis, then each time the delimiter is matched, the results (including any undefined results) of the sliding parentheses are spliced ​​into the output array.

You did not specify exactly what you want to achieve with your regular expression, perhaps you want something like this:

 var str = "ab((cd))ef"; var arr = str.split(/[\)\(]+/); console.log(arr); // ["ab", "cd", "ef"] 

EDIT:

Each bracket matches the regular expression individually, so the array looks like this (one line in brackets corresponds to:

 ['ab', '('] // matched ( ['ab', '(', '', '('] // matched ( (between the last two matches is the empty string ['ab', '(', '', '(', 'cd', ')'] // matched ) ['ab', '(', '', '(', 'cd', ')', '', ')'] // matched ) ['ab', '(', '', '(', 'cd', ')', '', ')', 'ef'] // string end 

EDIT2:

Required output: ["ab", "(", "(", "cd", ")", ")", "ef"]

I'm not sure you can do this with one split. The fastest and safest way to do this is to simply filter out blank lines. I doubt there is a single section solution for regex.

 var str = "ab((cd))ef"; var arr = str.split(/([\)\(])/).filter(function(item) { return item !== '';}); console.log(arr); 
+7
source

Interest Ask!

I'm not sure why, but if you're a chain

 .filter(function(el){ return el !== "";}); 

to your split, you can get rid of empty lines:

 var str = "ab((cd))ef"; var arr = str.split(/([\)\(])/).filter(function(el) { return el !== "";}); console.log(arr); // ["ab", "(", "(", "cd", ")", ")", "ef"] 
+3
source

Source: https://habr.com/ru/post/958250/


All Articles