Regular Expression to get a string between parentheses in Javascript

后端 未结 9 666
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 09:45

I am trying to write a regular expression which returns a string which is between parentheses. For example: I want to get the string which resides between the strings \"(\"

9条回答
  •  感情败类
    2020-11-22 10:12

    Try string manipulation:

    var txt = "I expect five hundred dollars ($500). and new brackets ($600)";
    var newTxt = txt.split('(');
    for (var i = 1; i < newTxt.length; i++) {
        console.log(newTxt[i].split(')')[0]);
    }
    

    or regex (which is somewhat slow compare to the above)

    var txt = "I expect five hundred dollars ($500). and new brackets ($600)";
    var regExp = /\(([^)]+)\)/g;
    var matches = txt.match(regExp);
    for (var i = 0; i < matches.length; i++) {
        var str = matches[i];
        console.log(str.substring(1, str.length - 1));
    }
    

提交回复
热议问题