Home > OS >  Remove all zeros in a number string based on condition
Remove all zeros in a number string based on condition

Time:01-31

I have an <input type='number'/> comp.

How would I be able to use the onSubmit (or other option, I'm free for suggestions, but I need it to not affect the user while he type, only when he finish) in order to do all of the following:

  1. Remove all leading zeros
  2. Remove all ending zeros
  3. Replace all of the zeros in the string to be single (a.k.a all multiple zeros will be converted to single for example 10020004 will be converted to 10204

By default the user will be able to enter how many he will want, the first two options will always be. the third option will be depending on user data (for the sake of the question lets say if first_user is set to true, it will be)

What I've tried so far is something like that ref.value.replace('/^0 /', '') (using ^0$ didn't work well for me, but condition number 3 I have no idea how to accomplish even a little) it works fine most of time on the starting zeros but I didn't find a way to do on the ending and on all of the middle stuff

Clarification to the thirst option:

based on the first_user state (true or false) it will remove the inside of the digit string, if its true then all inside zeros will be converted to single ones, if its false all inside zeros will be converted to double zeros

CodePudding user response:

A good solution would be to implement a simple algorithm that does what you need. Example:

  • Remove from the first position (0) on until you find a non-zero number;
  • Remove from the last position backwards (string.length-1) until you find a non-zero number;
  • Walk the string after the modification above and: if the current number is a non-zero create a new string with it, if it is zero and the previous was not, include it on the new string, if the previous was zero, ignore it.

That should make a very simple method and will work better then a regex. For the onSubmit trigger, I think it will work fine. I would use onChange and store it in a hidden field just, but I thing onSubmit will do the trick

CodePudding user response:

I think you're overthinking it. To replace multiples of anything with a single version of that thing you just need to target one or more things and in your replace function, replace with a single thing

You don't really need to specify the beginning or the end. You just need to specify any one or more 0 and then replace with a single 0

Try this:

const singleZeros = '10020004'.replace(/(0 )/g, '0')

console.log(singleZeros);

For removing the leading and trailing 0's, there might be a better way but off the top of my head, this is what I'd do:

const removeStart = (s) => s.startsWith('0') ? s.slice(1) : s;
const removeEnd = (s) => s.endsWith('0') ? s.slice(0, s.length - 1) : s;

const zerosOnEnds = '0102040'

const zerosTrimmed = removeEnd(removeStart(zerosOnEnds));


console.log(zerosTrimmed)

CodePudding user response:

Maybe a simple solution would be to create a conversion function to run on submit. Something like:

answer = 10020004
function transform(answer){

    final_answ = ''
    index = 0
    zero_index = -2
    while(index<answer.toString().length){
      if (answer.toString()[index] !== '0'){
        final_answ  = answer.toString()[index]
      } else if (index === zero_index 1){
        zero_index = index
      } else {
        final_answ  = answer.toString()[index]
        zero_index = index
      }
      index  
    }
}

Transforming the user response to string will also make it easy for you to remove starting and ending '0'. If this does not help will you please, provide more information? Hope it helps.

CodePudding user response:

You can try this

let str = '001002000400'
str = str.replace(/^0*(\d ?)0*$/, (matchs, p1) => { 
  return p1.replaceAll(/([^0] )0 /g,'$10')
})
console.log(str); //10204

CodePudding user response:

  • from your post all you need is just a regex to replace first zero with empty string and other zero in middle if they're more than 1 replace them and just keep one
  • what you will be need first thing in your code you're used the regex as string'/^0 /' and that's not the true way to use regex you should remove the string quotes and write your regex inside forward slash / like /regex/
  • second: you need to use regex modifiers in your case you need g modifier
  • for more info about regex you can check some tutorials like that or quick reference like w3schools reference
  • here's your regex
//Result: 104057
console.log("0100400057".replace(/^0|(0) (?=0)/g, ""))

CodePudding user response:

You can do this with a single replace call. The three cases can be checked in this order:

  • Zeroes at start of string
  • Zeroes at end of string
  • Zeroes (more than one) anywhere else: capture the first zero in capture group

As replacement, output the string captured by the capture group. As this group only captures a zero when the third case kicks in, this practically means that all other zeroes are removed.

I believe an exception to this rule has to be introduced for when the number is exactly 0. I guess you want to keep that single zero then. To make that happen, I would restrict the first two rules as follows:

  • Zeroes at start of string when followed by a non-zero
  • Zeroes at end of string when following a non-zero
  • Zeroes (more than one) anywhere else: capture the first zero in capture group

The third case will now also apply when the input consists of only zeroes.

You could use the submit event, but maybe it is interesting too to use the change event: it does not trigger while the user is typing, but does trigger when the user "commits" the value, i.e. when focus is moved to another element, or another tab/window is selected, or the up/down controls are used on the input widget, or the form is submitted, ...

document.getElementById("inp").addEventListener("change", function () {
    this.value = this.value.replace(/^0 (?=[^0])|(?<=[^0])0 $|(0)0 /g, "$1");
});
<input id="inp" type="number">

<button>Fake submit</button>

  • Related