Javascript - 删除粘贴上的空格 [英] Javascript - Removing spaces on paste

查看:1076
本文介绍了Javascript - 删除粘贴上的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入文本字段,maxlength为10.该字段用于澳大利亚电话号码(10位数字)。电话号码通常分为以下语法

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?

提前感谢。

推荐答案

这应该适用于您:

HTML

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

JavaScript

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

cleanPhoneNumber= function(e) {
    e.preventDefault();
    var pastedText = '';
    if (window.clipboardData && window.clipboardData.getData) { // IE
        pastedText = window.clipboardData.getData('Text');
      } else if (e.clipboardData && e.clipboardData.getData) {
        pastedText = e.clipboardData.getData('text/plain');
      }
    this.value = pastedText.replace(/\D/g, '');
};

phone.onpaste = cleanPhoneNumber;

小提琴: http://jsfiddle.net/y6TYp/6/

更新 nnnnnn对澳大利亚的电话号码有很大的意义,替换正则表达式。

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

这篇关于Javascript - 删除粘贴上的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆