Remove character from a generated value

3

How to get a value generated, check how many characters it has and remove if necessary? Example: If the value is only 4 characters (eg 1844) it ignores, but if it goes from 4 characters a function removes the characters to only 4, type if it has 6 characters (ex: 184455) remove 2 to only 4 again.

    
asked by anonymous 18.07.2016 / 15:06

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% with%

    
18.07.2016 / 15:16
3

Use the substring (start, end) method.

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

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

See the example that will remove the surplus characters when you exit the input (event blur).

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