Assuming that you will always have at least one digit in the input data, you can use this pattern /^0*(\d+?)0*$/
with exec()
and access the single capture group.
This uses just one capture group, no alternatives (pipes), and ensures at least one digit in the output, and doesn't seek multiple matches (no g
).
The capture group uses a lazy quantifier and the 0
s use greedy quantifiers for improved efficiency. Start and end anchors (^
and $
) are used to ensure the entire string is matched.
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 half the job to +
to cast the string to int (this has the added benefit of stabilizing the input when there is no length) and then let replace
handle right-side trimming.
The one-time lookbehind ((?<=\d)
) is used to ensure a minimum output length of one. Can I Use: Lookbehind in JS regular expressions
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*$/, "")));