Search code examples
javascriptstringparsingsubstringlastindexof

How can I use javascript to get a substring of whatever is between two parenthesis?


I am trying to return just "AA" using javascript.

This doesn't work.

var myStr = "Item Code Alpha Tengo (AA)"; 
var newStr = myStr.substring("(",myStr.lastIndexOf(")"));

Solution

  • You can also do:

    var myStr = 'Item Code Alpha Tengo (AA)';
    myStr.replace(/^[^(]*\(|\)[^)]*$/g, ''); // AA
    

    or the simpler:

    myStr.replace(/.*\(|\).*/g,'')