Detect text between open and closed keys in javascript [closed]


How can I detect when a key { opens and when } is closed? What I want to achieve is to detect the opening and closing of the keys, but I would also like to be able to detect content within them.


{#f66} o {red}

Expected result:

  • The keys: {#f66} and {red} .
  • And the content: #f66 and red .
  • asked by Eddy Otsutsuki 28.11.2016 в 02:02

    3 answers


    Regular expression:



    • { - Matches a literal key opening
    • ([^}]*) - Group 1 - Record the value of the text with which it coincided in a retro-reference. Coincides with:
      • [^}]* - Any character that is not a } , repeated 0 or more times
    • } - Matches a literal key lock

    When using a group (with parentheses), the result of RegExp.exec ( ) , it will be an array with all the coincidence in index 0, and the result of the first group in index 1 (or more if we used more groups).


    const texto = "{#f66} o {red}",
          regex = /{([^}]*)}/g;
    var grupos;
    while ((grupos = regex.exec(texto)) !== null) {
      console.log("Llaves:", grupos[0], "\tPosición:", grupos.index, "\tColor:", grupos[1]);
    answered by 28.11.2016 / 02:30

    To atom and to be able to know if your syntax is fine in JavaScript you have jslint For the theme of colors you have another plugin for Atom called color-picker. You can find them when searching in Atom

    answered by 28.11.2016 в 02:16

    If I understand correctly, you want to detect the value inside the keys, what you can do is use a regular expression and the method match that detects the opening key { , read what is inside (putting it in a parenthesis) and then the closing key { .

    Something like this /{(.*)}/ that you can see here:

    var aux = "{#f00}";
    var color = aux.match(/{(.*)}/);

    That will return an array with the string that met the condition and value within the keys.

    answered by 28.11.2016 в 02:17