Javascript - 如果字符串包含并替换

标签 javascript html

我一定是对这个函数犯了一个简单的错误或误解。正如您在下面看到的,当用户输入“-”时,我尝试将“-”替换为“/”。我正在尝试这样做,如果用户输入 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/

相关文章:

javascript - 登录后添加 Facebook 个人资料图片吗?

html - 无法阻止初始比例 = 1 的 iPhone 缩放

css - 为列表设置导航栏

javascript - 通过解析 innerHTML 添加几个 css 属性

javascript - 如何用lodash改进这个例程?

javascript - 为列表中的单个项目打开一个弹出窗口

JqueryUI Spinner 问题

html - 如何解决 CSS 的对齐问题

java - 在 Java 中合并 HTML 文件

javascript - 语法错误: <a> link not working by clicking,只能通过右键+ "open link in new tab"命令打开