0

Javascript Regular Expressions not behaving the way I anticipate. For the below string, I wish to only capture the sub-string inside special chars '["' & '"]'. I'm not able to de-reference '["' & '"]' and having a problem with these special characters. How can I just select the sub-string of interest inside the delimeters?

let myStr = '{"ReportParameters":["This is for a special client."]}';
console.log(myStr);


var myRegexp = new RegExp("^.*\[\"(.*)\"\].*$", "g");
match = myRegexp.exec(myStr);
if (match != null) {
    console.log(match[0])
}

This also does not work:

var myRegexp = /^.*\[(.*)\].*$"/g;

1 Answers1

-1

Your first regex is correct. But you have to access the matched group and not the complete match. Like this:

let myStr = '{"ReportParameters":["This is for a special client."]}';
console.log(myStr);


var myRegexp = new RegExp("^.*\[\"(.*)\"\].*$", "g");
const match = myRegexp.exec(myStr);
if (match != null) {
    console.log(match[1])
}

match is an array. The first element is always the complete match. After that follow the match groups in the same order as they are in the regex.

Edit: I just noticed that the above code only works in the browser but not in nodejs. Here is a work around:

var myRegexp = /^.*\["(.*)"\].*$/g;
IchEben
  • 35
  • 1
  • 4
  • You may want to use an online regex tool eg: https://regex101.com/ It shows you what exactly got matched and in which group it is. – IchEben Oct 14 '22 at 19:52
  • 1
    As it turns out, the brackets need to be double escaped where as a single escape is required for a double quote. Example: \\[\". Not sure why this is but it now works. Thanks for the feedback. – Mark Johnson Oct 14 '22 at 20:17