Research:
After having searched in Stack Overflow, I have only found two solutions, both of which using Regular Expressions
and they can be found here:
→ (?<=\[)(.*?)(?=\])
(1)
(?<=\[)
: Positive Lookbehind.
\[
:matches the character [
literally.
(.*?)
: matches any character except newline and expands as needed.
(?=\])
: Positive Lookahead.
\]
: matches the character ]
literally.
→ \[(.*?)\]
(2)
\[
: matches the character [
literally.
(.*?)
: matches any character except newline and expands as needed.
\]
: matches the character ]
literally.
Notes:
(1) This pattern throws an error in JavaScript
, because the lookbehind operator is not supported.
Example:
console.log(/(?<=\[)(.*?)(?=\])/.exec("[a][b][c][d][e]"));
Uncaught SyntaxError: Invalid regular expression: /(?<=\[)(.*?)(?=\])/: Invalid group(…)
(2) This pattern returns the text inside only the first pair of square brackets as the second element.
Example:
console.log(/\[(.*?)\]/.exec("[a][b][c][d][e]"));
Returns: ["[a]", "a"]
Solution:
The most precise solution for JavaScript
that I have come up with is:
var string, array;
string = "[a][b][c][d][e]";
array = string.split("["); // → ["", "a]", "b]", "c]", "d]", "e]"]
string = array1.join(""); // → "a]b]c]d]e]"
array = string.split("]"); // → ["a", "b", "c", "d", "e", ""]
Now, depending upon whether we want the end result to be an array or a string we can do:
array = array.slice(0, array.length - 1) // → ["a", "b", "c", "d", "e"]
/* OR */
string = array.join("") // → "abcde"
One liner:
Finally, here's a handy one liner for each scenario for people like me who prefer to achieve the most with least code or our TL;DR
guys.
Array:
var a = "[a][b][c][d][e]".split("[").join("").split("]").slice(0,-1);
/* OR */
var a = "[a][b][c][d][e]".slice(1,-1).split(']['); // Thanks @xorspark
String:
var a = "[a][b][c][d][e]".split("[").join("").split("]").join("");