Search code examples
javascriptjquerysubstring

How to get the substring from between two [ ] braces in a string in javascript or jquery


My string looks like this street no [12]

I need to extract the 12 alone from the string.

How do I get the substring between two [ ] in javascript or jquery?

find the substring between first matching [] brackets


Solution

  • I noted that your requirements changed in a comment below the previous answer, to fix that issue you can change the regex adding ? so it will capture the least possible matches.

    const myString = "street no [12][22]"
    const match = myString.match(/\[(.+?)\]/);
    const myNumber = match && match[1];
    console.log(myNumber);

    Or, you can just capture digits if that works better for your needs

    const myString = "street no [12][22]"
    const match = myString.match(/\[(\d+)\]/);
    const myNumber = match && match[1];
    console.log(myNumber);