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>
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>
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]);
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":["¥"]}
We can remove:
^[^\[]*\[
\][^\]]*$
ie replace ( /(a)|(b)/,""
):
var n = '<HR>\n[{"key":"value","key2":["¥"]}]\n<HR>';
console.log(n.replace(/^[^\[]*\[|\][^\]]*$/g, ""));