Get text between two rounded brackets

后端 未结 5 1501
小蘑菇
小蘑菇 2020-11-29 08:19

How can I retrieve the word my from between the two rounded brackets in the following sentence using a regex in JavaScript?

\"This is (my

相关标签:
5条回答
  • 2020-11-29 08:23
    var txt = "This is (my) simple text";
    re = /\((.*)\)/;
    console.log(txt.match(re)[1]);​
    

    jsFiddle example

    0 讨论(0)
  • 2020-11-29 08:25

    You may also try a non-regex method (of course if there are multiple such brackets, it will eventually need looping, or regex)

    init = txt.indexOf('(');
    fin = txt.indexOf(')');
    console.log(txt.substr(init+1,fin-init-1))
    
    0 讨论(0)
  • console.log(
      "This is (my) simple text".match(/\(([^)]+)\)/)[1]
    );

    \( being opening brace, ( — start of subexpression, [^)]+ — anything but closing parenthesis one or more times (you may want to replace + with *), ) — end of subexpression, \) — closing brace. The match() returns an array ["(my)","my"] from which the second element is extracted.

    0 讨论(0)
  • 2020-11-29 08:35

    For anyone looking to return multiple texts in multiple brackets

    var testString = "(Charles) de (Gaulle), (Paris) [CDG]"
    var reBrackets = /\((.*?)\)/g;
    var listOfText = [];
    var found;
    while(found = reBrackets.exec(testString)) {
      listOfText.push(found[1]);
    };
    
    0 讨论(0)
  • 2020-11-29 08:44

    to return multiple items within rounded brackets

     var res2=str.split(/(|)/);
    
      var items=res2.filter((ele,i)=>{
      if(i%2!==0) {
      return ele;
      }
    });
    
    0 讨论(0)
提交回复
热议问题