Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Removing spaces on paste

I have an input text field with a maxlength of 10. The field is for Australian phone numbers (10 digits). Phone numbers are generally split up into the following syntax

12 12345678

If someone copies the above and pastes that into my input field, it obviously leaves the last digit out and keeps the space.

Is there a way to remove any spaces right before it is pasted into the input box? Or is there another work around?

Thanks in advance.

like image 263
Matt Avatar asked Aug 13 '12 23:08

Matt


People also ask

How to get rid of space in JavaScript?

JavaScript String trim() The trim() method removes whitespace from both sides of a string.

How to remove extra space between words in JavaScript?

For removing extra spaces, you can use the predefined JavaScript methods, including replace() method, split() method, or trim() method. The trim() method removes the spaces at the start of the string, while the replace() method removes extra spaces between words. The split() method removes all the spaces between words.


1 Answers

This should work for you:

HTML

<input type="text" id="phone" maxlength="10" />​

JavaScript

var phone = document.getElementById('phone'),
    cleanPhoneNumber;

cleanPhoneNumber= function(e)
{
 e.preventDefault();
 var pastedText = '';

 if (e.clipboardData && e.clipboardData.getData)
 {// Standards Compliant FIRST!
  pastedText = e.clipboardData.getData('text/plain');
 }
 else if (window.clipboardData && window.clipboardData.getData)
 {// IE
  pastedText = window.clipboardData.getData('Text');
 }

 this.value = pastedText.replace(/\D/g, '');
};

phone.onpaste = cleanPhoneNumber;

Fiddle: http://jsfiddle.net/y6TYp/6/

Update nnnnnn had a great point regarding Australian phone numbers, updating replace regex.

like image 186
Paul Avatar answered Sep 21 '22 09:09

Paul