删除输入框es6中的所有空白

时间:2018-10-24 12:54:15

标签: javascript javascript-events

我正在尝试删除用户在输入框中输入内容时的所有空白。我最初尝试使用3个单独的方法:regex用于在粘贴文本时删除空格,一个用于在按下空格键时删除空格,以及一个简单的修饰。注意:要求我使用类来调用方法。不知道从这里去哪里...我感谢您的帮助!谢谢:)

(function () {
class Digit {

// when user enters keys, do not allow spaces
    
    method2(userInput) {
        console.log({userInput});
        console.log("formatInput");
        const input = userInput.target.value;
        console.log(input.length);
        if (!input.length) return;  
        if (userInput.which === 32) { // 32 is space key
            console.log("this is a space");
            userInput.value = this.method1();
        } 
    }

    method1() {
        console.log("trimthis input");
        return userInput.trim(); 
    }

// when user pastes input remove spaces
    method3() {
        console.log("formatPaste");
        const reg = new RegExp(/\s+/, "");
            console.log(this.userInput);
            return this.userInput.replace(reg, "");
    }
}

const userInput = document.querySelector("#inputNumber");
console.log("User inputs", {userInput});
const digitObject = new Digit();
console.log(digitObject);
userInput.addEventListener("keyup", function() { digitObject.method2(); }, false);
digitObject.method3();
}());
<!DOCTYPE html>
<html lang="en">
    
<head> 
    
	<meta charset="UTF-8">
	<title>Numbers App</title>
	
    <!-- Google Fonts -->
	<link href="https://fonts.googleapis.com/css?family=Open+Sans|Roboto:400,500" rel="stylesheet">
    
    <!-- CSS -->
	<link rel="stylesheet" href="style.css">
    
</head>
    
<body>
    <!-- ASSIGNMENT: create page where user can type/save numbers only, css grid -->

    <div class="wrapper">
    <!-- simple form with number input and submit function, auto trim spaces -->
        <form>
            <div class="form">
                <div>
                    <input class="input--number has-float-label go-bottom Digit" id="inputNumber" placeholder="Enter Number" type="text" required />
                    <label for="inputNumber">Input</label>
                </div>
                <div class="btn--group">
                    <input type="button" value="Post" class="btn post" title="Post">
                    <input type="button" value="Clear" class="btn clear" title="Clear">
                </div>
            </div>
        </form>
    
    <!-- saved numbers table with date submitted -->


<!---->

    </div> <!-- end wrapper -->
    
    <!-- footer -->
   
    <!-- Javascript -->
    <script src="script.js"></script>
    
</body>
</html>

1 个答案:

答案 0 :(得分:0)

使用事件input捕获各种更改以及以下正则表达式/ /g

document.getElementById('textfield').addEventListener('input', function() {
  this.value = this.value.replace(/ /g, '');
});
<input id='textfield'>