Javascript regex - how to get text between curly brackets

后端 未结 2 475
逝去的感伤
逝去的感伤 2021-01-05 05:08

I need to get the text (if any) between curly brackets. I did find this other post but technically it wasn\'t answered correctly: Regular expression to extract text between

相关标签:
2条回答
  • 2021-01-05 05:33

    Create a "capturing group" to indicate the text you want. Use the String.replace() function to replace the entire string with just the back reference to the capture group. You're left with the text you want.

    0 讨论(0)
  • 2021-01-05 05:38

    To extract all occurrences between curly braces, you can make something like this:

    function getWordsBetweenCurlies(str) {
      var results = [], re = /{([^}]+)}/g, text;
    
      while(text = re.exec(str)) {
        results.push(text[1]);
      }
      return results;
    }
    
    getWordsBetweenCurlies("Some random {stuff} in this {sentence}");
    // returns ["stuff", "sentence"]
    
    0 讨论(0)
提交回复
热议问题