I want to ignore 0 in the regex below. Currently, the regex returns an array and splitting the characters into n digits. I want the regex to ignore character 0.
var n = 2
var str = '123045';
var regex2 = new RegExp(`.{1,${n}}`,'g');
var reg = str.match(regex2)
One way you could achieve this is by removing the 0
before you perform your match. This can be done by using .replace()
like so:
const n = 2 const str = '123045'; const regex2 = new RegExp(`.{1,${n}}`, 'g'); const reg = str.replace(/0/g, '').match(regex2); console.log(reg); // ['12', '34', '5']
To ignore leading zeros, you can match for 0
followed by n
amount of digits for each element in your matched array (using .map()
) and .replace()
this with the remaining digits by capturing them in a group, and using the group as the replacement:
const n = 2 const str = '123045'; const regex2 = new RegExp(`.{1,${n}}`, 'g'); const reg = str.match(regex2).map(m => m.replace(/0(\\d+)/g, '$1')).join('').match(regex2); console.log(reg); // ['12', '30', '45']
Best way is to use replace,
But if you want to do it using regex try (?!0)[\\d]
It shall give you matches 1,2,3,4,5
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.