Javascript function need allow numbers, dot and comma(Javascript 函数需要允许数字、点和逗号)
问题描述
我需要创建一个函数来允许数字点和逗号.所以任何人纠正以下功能
I need to create a function to allow numbers dot and comma. So anyone corrects the following function
function on(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]|./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
推荐答案
首先,您的正则表达式当前不允许逗号,这是您的要求.
Firstly your regex currently doesn't allow comma, which is your requirement.
其次,您没有使用任何量词,因此您的正则表达式将仅匹配单个字符 - [0-9]
或 dot
之一.您需要使用量词.
Secondly, you haven't used any quantifier, so your regex will match only a single character - one of [0-9]
or a dot
. You need to use a quantifier.
第三,不使用管道
,你可以只移动字符类中的所有字符.
Thirdly, instead of using pipe
, you can move all characters inside the character class only.
尝试使用以下正则表达式:
Try using the below regex:
/^[0-9.,]+$/
量词 +
用于匹配 1 次或多次出现的模式.^
和 $
锚分别匹配字符串的开头和结尾.
Quantifier +
is used to match 1 or more occurrence of the pattern.
^
and $
anchors match the beginning, and end of the string respectively.
这篇关于Javascript 函数需要允许数字、点和逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Javascript 函数需要允许数字、点和逗号


基础教程推荐
- Chart.js 在线性图表上拖动点 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01