Remove leading and trailing zeros from a string
You can just combine both of your regex using an OR
clause (|
):
var r = '00001011100000'.replace(/^0+|0+$/g, "");
//=> "10111"
update: Above regex solutions replaces 0
with an empty string. To prevent this problem use this regex:
var repl = str.replace(/^0+(\d)|(\d)0+$/gm, '$1$2');
RegEx Demo
RegEx Breakup:
^
: Assert start0+
: Match one or more zeroes(\d)
: Followed by a digit that is captured in capture group #1|
: OR(\d)
: Match a digit that is captured in capture group #20+
: Followed by one or more zeroes$
: Assert end
Replacement:
Here we are using two back-references of the tow capturing groups:
$1$2
That basically puts digit after leading zeroes and digit before trailing zeroes back in the replacement.
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*$/, "")));