Sample input
var abc = "blah blah [abc] , [123] [ab12], [456] [cdef] 789 ghi000 "
Expected output
["123", "456"]
I am trying to write regex that should match only the numbers within the square brackets and return an array of those numbers (excluding the []).
The regex that I tried used lookbehind so it worked from Chrome but failed for firefox. I found later that lookbehind is not yet supported in firefox (Visit https://bugzilla.mozilla.org/show_bug.cgi?id=1225665 ).
abc.match(/(?<=\[)(\d+)/g);
I get the expected output on Chrome 76:
["123", "456"]
but I get error on Firefox 68:
SyntaxError: invalid regexp group
How can I write a regex that works on both and generate expected result.
You can use match
and map
var abc = "blah blah [abc] , [123] [ab12], [456] [cdef] 789 ghi000 " let output = abc.match(/\\[\\d+\\]/g).map(m=>m.replace(/\\[(\\d+)\\]/g, "$1")) console.log(output)
Or you can use exec
var regex1 = /\\[(\\d+)\\]/g var str1 = "blah blah [abc] , [123] [ab12], [456] [cdef] 789 ghi000 " var array1; while ((array1 = regex1.exec(str1)) !== null) { console.log(`Found ${array1[1]}`); }
Use capturing groups, eg:
var abc = "blah blah [abc] , [123] [ab12], [456] [cdef] 789 ghi000 ";
Array.from(abc.matchAll(/\[(\d+)\]/g)).map(m => m[1])
matchAll (note the browser compatibility) finds every occurrence of [NNN]
and captures the digits inside the square brackets as match[1]
.
Array.from()
converts the iterator returned from matchAll
to an array, which can then be processed to extract the capture.
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.