Home  >  Q&A  >  body text

javascript - Questions about regular expressions

<!DOCTYPE html>
 <html lang="en">
 <head>
 <meta charset="utf-8" />
 <title>判断数字是否为两位数</title>
 <style type="text/css">
body {font: 12px/1.5 arial;text-align: center;}
.f-text {width: 50px;border: 1px solid #ccc;background:     #f0f0f0;font-family: inherit;padding: 3px;margin-right: 10px;}
</style>
<script type="text/javascript">
window.onload = function() {
var aInput = document.getElementsByTagName("input");
var aSpan = document.getElementsByTagName("span")[0];
var i = 0;
aInput[0].onkeyup = function() {
 this.value = this.value.replace(/[^\d]/,"");
}
 aInput[1].onclick = function() {
(aInput[0].value == "") ?
alert("请输入数字!") :
alert(/^\d{2}$/.test(parseInt(aInput[0].value)) ? "√ 是两位数" :  "这是" + aInput[0].value.length + "位数");
}
};
</script>
</head>

 <body>
 <input type="text" class="f-text" /><input type="button"     value="是  否为两位数" />    
 </body>
 </html>
What does the "" in

1.this.value = this.value.replace(/1/,"") mean?


  1. d ↩
给我你的怀抱给我你的怀抱2662 days ago692

reply all(2)I'll reply

  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-07-05 10:52:08

    [^d] represents a character that is not a number, where d represents any number from 0-9`, [^...] represents the inversion of the character set

    Therefore, this.value.replace(/[^d]/,"") means that if the first character of the string is a number, keep it; if it is not a number, delete it

    For example, the first character of
    2asd and 3adf is a number and will not be replaced; the first character of
    sadf and a123 is not a number and will be replaced by the empty string "" , that is, delete the character

    reply
    0
  • 大家讲道理

    大家讲道理2017-07-05 10:52:08

    "" means empty. replace means replacement; [^d] means non-digit (^ means non, meaning not; d means number)

    means that when you type (every time you tap the keyboard), a keyboard event will be triggered. If the input is not a number ([^d] means non-number, so use [^d] to determine whether it is a number), then replace it. (.replace means replacement) is empty (""), so if you enter something other than a number, it will be replaced immediately and will not be displayed.

    reply
    0
  • Cancelreply