First and last character occurrence

Asked

Viewed 1,468 times

2

In Javascript, how to extract from a string everything that is between the first occurrence of [ and the last occurrence of ] ?

Ex:

<HR>\n[{"key":"value","key2":["¥"]}]\n<HR>
  • You mean catch macros? Take a look at Junior Nunes' answer at this link: https://answall.com/questions/197479/como-pega-macros-v%C3%A1riaveis-em-uma-string

3 answers

3


You can use \[(.*)\] and then only get the captured part.
Or use \[.*\] and make a Slice to the string that this generates.

You can see that operating 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]);

1

Use the exec command of the regular expression. 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":["¥"]}

0

We can remove:

  • (a) from start until [ ^[^\[]*\[
  • (b) from ] until the end \][^\]]*$

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

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.