0

I have a string as follows:

var str = 'Array
(
    [shopUsername] => tod
    [password] => 12345678
    [shopID] => 19
)';

I'm trying to parse this in JavaScript using the following regular expression:

var matches = parsedXMLStr.match(/\[(.*)\]/g);

which returns each of the key values as [ '[shopUserName]', '[password]', '[shopID]' ].

How do I change the regular expression to strip out the square brackets from the returned values, i.e. the array should be ['shopUserName', 'password','shopID'].

Richard
  • 6,812
  • 5
  • 45
  • 60
LeDoc
  • 935
  • 2
  • 12
  • 24
  • get the group from index 1. – Braj Apr 20 '15 at 11:20
  • Use `exec` instead. See: http://stackoverflow.com/questions/19913667/javascript-regex-global-match-groups – Halcyon Apr 20 '15 at 11:22
  • Is this string being emitted from a PHP service that can be modified? (if so, you could try something like `json_encode`, see: http://stackoverflow.com/a/16118772/344143) – Ben Mosher Apr 20 '15 at 11:24
  • if the brackets are properly closed the you may consider this `[^\[\]]*(?=\])`, https://regex101.com/r/fU4hC6/1 – Avinash Raj Apr 20 '15 at 11:26

2 Answers2

3

Use exec to grab the groups:

var str = 'Array(    [shopUsername] => tod\n    [password] => 12345678\n    [shopID] => 19)';
var match;
var results = [];
var regex = new RegExp(/\[(.*)\]/g);
while(match = regex.exec(str)) {
    results.push(match[1]);
}
console.log(results);

jsFiddle

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
0

try using

str.replace(/[\[\]']+/g,'')