Remove leading and trailing zeros from a string

20,430

Solution 1

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 start
  • 0+: 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 #2
  • 0+: 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.

Solution 2

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 0s 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*$/, "")));
Share:
20,430
Lior Elrom
Author by

Lior Elrom

I'm a software engineer who like to learn and explore new technologies and not afraid to ask questions when needed.

Updated on November 26, 2020

Comments

  • Lior Elrom
    Lior Elrom over 3 years

    I have a few strings like so:

    str1 = "00001011100000";  // 10111
    str2 = "00011101000000";  // 11101
    ...
    

    I would like to strip the leading AND closing zeros from every string using regex with ONE operation.

    So far I used two different functions but I would like to combine them together:

    str.replace(/^0+/,'').replace(/0+$/,'');
    
  • dvsoukup
    dvsoukup almost 7 years
    I know this is a pretty old thread, but it still comes up in google search when trying to trim leading/trailing zeros. While this works most of the time, it doesn't properly handle a value of '0'. It just trims it out completely, while 0 is technically a valid number.
  • anubhava
    anubhava about 6 years
    I have upvoted your answer to neutralize a downvote. However I think downvote may be because of your use of lookbehind which is not supported in all browsers's JS engines.
  • mickmackusa
    mickmackusa about 6 years
    Oh. I didnt know that. Thx
  • wonsuc
    wonsuc over 5 years
    This answer really helped me. However I can't wirte these kind of values: 1.005
  • user192344
    user192344 almost 4 years
    well, you are incorrect, we are talking about string, not number, not digits
  • anubhava
    anubhava almost 4 years
    Sorry who is incorrect and for which input this didn't work?