Assuming you always have at least one digit in the input, you can use this template /^0*(\d+?)0*$/ s exec() and access one capture group.
In this case, only one capture group is used, without alternatives (channels), and at least one digit in the output is provided, and several matches are not searched (without g ).
The capture group uses lazy quantifiers, and 0 greedy quantifiers to increase efficiency. Start and end anchors ( ^ and $ ) are used to ensure that the entire string is consistent.
console.log('0001001000 => '+ /^0*(\d+?)0*$/.exec("00100100")[1]); console.log('001 => ' + /^0*(\d+?)0*$/.exec("001")[1]); console.log('100 => ' + /^0*(\d+?)0*$/.exec("100")[1]); console.log('1 => ' + /^0*(\d+?)0*$/.exec("1")[1]); console.log('0 => ' + /^0*(\d+?)0*$/.exec("0")[1]); console.log('11 => ' + /^0*(\d+?)0*$/.exec("11")[1]); console.log('00 => ' + /^0*(\d+?)0*$/.exec("00")[1]); console.log('111 => ' + /^0*(\d+?)0*$/.exec("111")[1]); console.log('000 => ' + /^0*(\d+?)0*$/.exec("000")[1]);
Or you can shift the half of the job by + to bring the string to int (this gives the added benefit of stabilizing input when there is no length), and then enable replace the trim handle on the right.
A one-time lookback ( (?<=\d) ) is used to provide a minimum output length of one.
console.log('0001001000 => ' + (+'0001001000'.replace(/(?<=\d)0*$/, ""))); console.log('[empty] => ' + (+''.replace(/(?<=\d)0*$/, ""))); console.log('001 => ' + (+'001'.replace(/(?<=\d)0*$/, ""))); console.log('100 => ' + (+'100'.replace(/(?<=\d)0*$/, ""))); console.log('1 => ' + (+'1'.replace(/(?<=\d)0*$/, ""))); console.log('0 => ' + (+'0'.replace(/(?<=\d)0*$/, ""))); console.log('11 => ' + (+'11'.replace(/(?<=\d)0*$/, ""))); console.log('00 => ' + (+'00'.replace(/(?<=\d)0*$/, ""))); console.log('111 => ' + (+'111'.replace(/(?<=\d)0*$/, ""))); console.log('000 => ' + (+'000'.replace(/(?<=\d)0*$/, "")));
source share