Angel Politis
Angel Politis

Reputation: 11313

How to extract text in square brackets from string in JavaScript?

How can I extract the text between all pairs of square brackets from the a string "[a][b][c][d][e]", so that I can get the following results:

Array: ["a", "b", "c", "d", "e"]

String: "abcde"

I have tried the following Regular Expressions, but to no avail:

(?<=\[)(.*?)(?=\])

\[(.*?)\]

Upvotes: 1

Views: 2556

Answers (3)

Angel Politis
Angel Politis

Reputation: 11313

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)

  1. (?<=\[) : Positive Lookbehind.
  2. \[ :matches the character [ literally.
  3. (.*?) : matches any character except newline and expands as needed.
  4. (?=\]) : Positive Lookahead.
  5. \] : matches the character ] literally.

\[(.*?)\] (2)

  1. \[ : matches the character [ literally.
  2. (.*?) : matches any character except newline and expands as needed.
  3. \] : 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("");

Upvotes: 1

Alex Kudryashev
Alex Kudryashev

Reputation: 9460

I think this approach will be interesting to you.

    var arr = [];
    var str = '';
    var input = "[a][b][c][d][e]";
    input.replace(/\[(.*?)\]/g, function(match, pattern){
      arr.push(pattern);
      str += pattern;
      return match;//just in case ;)
    });
    
    console.log('Arr:', arr);
    console.log('String:', str);

//And trivial solution if you need only string
var a = input.replace(/\[|\]/g, '');
console.log('Trivial:',a);

Upvotes: 0

char
char

Reputation: 91

I don't know what text you are expecting in that string of array, but for the example you've given.

var arrStr = "[a][b][c][d][e]";
var arr = arrStr.match(/[a-z]/g) --> [ 'a', 'b', 'c', 'd', 'e' ] with typeof 'array'

then you can just use `.concat()` on the produced array to combine them into a string.

if you're expecting multiple characters between the square brackets, then the regex can be (/[a-z]+/g) or tweaked to your liking.

Upvotes: 0

Related Questions