Remove character from a generated value

Asked

Viewed 22 times

3

Can you take a generated value, check how many characters you have, and remove if necessary? Example: If the value is only 4 characters (ex: 1844) it ignores, but if you pass 4 characters a function removes the characters to only 4, type if it has 6 characters (ex: 184455) remove 2 to only 4 again.

2 answers

3


Do so

function remove_chars(num) {
  var str_num = String(num);
  if(str_num.length > 4) {
    var removals = str_num.length - 4;
    str_num = str_num.slice(0, -removals);
  }
  if(isNaN) {
       return str_num;
  }
  return parseInt(str_num);
}
console.log(remove_chars(325325));

Note: If you are sure that they are always numbers, you can remove if(isNaN) {return str_num;}

3

Use the method substring(start, end).

The method has two parameters to define what will be extracted:

  • The first parameter you set the initial index you want - in the first char start example (0).
  • The second parameter you define how many characters you want to extract - in the example I want only the first 4 after zero position.

See the example that will remove excess characters when exiting input (Blur event).

var $meuTxt = document.getElementById('meuTxt');
$meuTxt.addEventListener('blur', function() {
  var valor = this.value;
  this.value = valor.substring(0, 4);
});
<input type="text" id="meuTxt" />

Browser other questions tagged

You are not signed in. Login or sign up in order to post.