Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
729 views
in Technique[技术] by (71.8m points)

events - How to insert - after 6th character and after 8th character in Javascript?

Hello everyone and my problem faced is when user key in Malaysian Identity Card "930402084401", I want the key in number to automatically add - to become "930402-08-4401".

When User key in 930402084401

What I want in my textbox => 930402-08-4401

I try to refer to the code where the code will automatically add space every 4 numbers, but I totally have no idea how to change the code.

document.getElementById('creditSpace').addEventListener('input', function(e) {
  var target = e.target,
    position = target.selectionEnd,
    length = target.value.length;

  target.value = target.value.replace(/[^dA-Z]/g, '').replace(/(.{4})/g, '$1 ').trim();
  target.selectionEnd = position += ((target.value.charAt(position - 1) === ' ' && target.value.charAt(length - 1) === ' ' && length !== target.value.length) ? 1 : 0);
});
<label><input id="creditSpace"> CC Details </label>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
var s = '930402084401';
var t = s.replace( /(d{6})(d{2})(d{4})/, '$1-$2-$3' ); // 930402-08-4401

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...