我一定是对这个函数犯了一个简单的错误或误解。正如您在下面看到的,当用户输入“-”时,我尝试将“-”替换为“/”。我正在尝试这样做,如果用户输入 12-12-12。它将立即替换所有 3 个虚线,例如:用户输入 12- 功能立即变为 12/。
我在这里做错了什么。
function onkey(){
var user_input = document.getElementById('date_val').value;
// if(user_input.includes("-")){
// console.log("detects")
// user_input.replace(/-/g, "/");
// }
user_input.includes("-")? console.log("detects") && user_input.replace(/-/g, "/"):user_input;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
date :<input type="text" id="date_val" onkeyup="onkey()">
<script src="./js/test.js"></script>
</body>
</html>
最佳答案
您需要分配函数 replace
的结果。
Adopt the function
addEventListener
to bind events to your elements.
document.getElementById('date_val').addEventListener('keyup', function() {
this.value = this.value.replace(/-/g, "/");
});
Date :<input type="text" id="date_val">
这是使用事件 input
捕获该输入字段中的每个更改的替代方法。
This way, you will provide a better user experience and will be handled every change like a drag, drop and text paste as well. Look how while you're writing the replacement is not visible.
document.getElementById('date_val').addEventListener('input', function() {
this.value = this.value.replace(/-/g, "/");
});
Date :<input type="text" placeholder="Paste, Drag & Drop text" id="date_val">
关于Javascript - 如果字符串包含并替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49519190/