Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/472.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
仅使用javascript提取数字_Javascript_Regex_Preg Replace - Fatal编程技术网

仅使用javascript提取数字

仅使用javascript提取数字,javascript,regex,preg-replace,Javascript,Regex,Preg Replace,我只需要从下拉列表中的选项文本中提取至少2个但不超过3个数字,然后将其显示在输入字段中。我读过关于regexp的书,认为我已经完全弄明白了。但我似乎无法让它发挥作用 <script> function copyEbc() { var a = document.getElementById("malt"); // the <select> var onlydig = /\d{1,3}/ // regexp var option = a.options[a.selectedI

我只需要从下拉列表中的选项文本中提取至少2个但不超过3个数字,然后将其显示在输入字段中。我读过关于regexp的书,认为我已经完全弄明白了。但我似乎无法让它发挥作用

<script>
function copyEbc() {
var a = document.getElementById("malt"); // the <select>
var onlydig = /\d{1,3}/ // regexp
var option = a.options[a.selectedIndex].text(onlydig); // regexp on options
var txt = document.getElementById("ebc").value;
txt = txt + option;
document.getElementById("ebc").value = txt;

}
</script>
例如,我只想从一个选中的选项中选择4,并使用文本Pilsner 4 EBC

我在这里完全迷路了吗

非常感谢您的输入,干杯

您试图将文本值作为一个函数调用,您的JS控制台可能对此有所抱怨

而是与正则表达式匹配。匹配[0]将包含匹配的文本:

var option = a.options[a.selectedIndex].text.match(onlydig)[0];

要简单地从字符串中提取数字,请使用匹配:


您需要使用regexp对象的match方法。AFAIK您正在使用的文本方法不存在。

Try/^\d{3}$/用于您的正则表达式。这将得到3个数字。正则表达式的乐趣,这里有一个很好的引用。有些人在遇到问题时认为我知道,我会使用正则表达式。现在他们有两个问题。好吧,新问题现在:如果我在列表中选择一个新选项,例如巧克力麦芽800 EBC,它只需将数字添加到先前选择的已经选择的数字中,现在显示为4800。我只想清除字段并添加新选择中的数字。有办法解决吗?document.getElementByIdebc.value=option;
var numberPattern = /\d+/g;
var foo = 'Pilsner 4 EBC';
var numbers = foo.match(numberPattern);
alert(numbers); // alerts the array of numbers