First and last occurrence of character

2

In JavaScript, how do you extract from a string anything between the first occurrence of [ and the last occurrence of ] ?

Ex:

<HR>\n[{"key":"value","key2":["¥"]}]\n<HR>
    
asked by anonymous 06.07.2017 / 13:23

3 answers

3

You can use \[(.*)\] and then fetch only the captured part. Or use \[.*\] and make a slice to the string it generates.

You can see this running here , or in the example:

var string = '<HR>\n[{"key":"value","key2":["¥"]}]\n<HR>';

var semCaptura = /\[.*\]/;
var comCaptura = /\[(.*)\]/;

console.log('semCaptura', string.match(semCaptura)[0].slice(1, -1));
console.log('comCaptura', string.match(comCaptura)[1]);
    
06.07.2017 / 13:34
1

Use the regular expression exec command. It would look like this:

var regex = /\[(.*)\]/g;
var string = '<HR>\n[{"key":"value","key2":["¥"]}]\n<HR>';

var finds = regex.exec(string);
console.log(finds); // Todas ocorrências encontradas

console.log(finds[1]); //{"key":"value","key2":["¥"]}
    
06.07.2017 / 13:33
0

We can remove:

  • (a) from the beginning to [ ^[^\[]*\[
  • (b) of] to the end \][^\]]*$

ie replace ( /(a)|(b)/,"" ):

var n = '<HR>\n[{"key":"value","key2":["¥"]}]\n<HR>';

console.log(n.replace(/^[^\[]*\[|\][^\]]*$/g, ""));
    
07.07.2017 / 12:23