简体   繁体   中英

Get the first matched number between square brackets

I have a string like the following woocommerce_click_and_pick_shipping_branch[1] , and I want to use regEx to get the number between the square bracket.

I've tried the following with no luck:

replace([^\\[\\]]+)(?=\\]\\[[^\\]]+\\]$)

You could use the following:

var str = "woocommerce_click_and_pick_shipping_branch[14432]".match(/\[(\d*)\]/);

if (str) {
  console.log(str[1]); // 14432
}

Example Here

You could do something like this: http://jsfiddle.net/3cm7321x/1 This will loop through your string and when it finds an integer the if statement is true and it will return you the number.

var str= "woocommerce_click_and_pick_shipping_branch[1234]";
var number="";
for (i=0; i<str.length; i++) {
    if (str[i] % 1 === 0){
        number +=str[i]; 
    }
}

alert(number);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM