javascript - 如何使用正则表达式仅获取字符串的特定部分?
问题描述
在输入字段中,我有值A=123
,我需要 JavaScript 代码才能只获取该123
部分。
这是我到目前为止所尝试的:
function formAnswer() {
var input = document.getElementById('given').value;
var match = input.match(/A=.*/);
document.getElementById('result').value = match;
}
<input type="text" id="given" placeholder="Given" value="A=123"/>
<input type="text" id="result" placeholder="Result"/>
<input type="button" value="Click!" onClick="formAnswer();"/>
但这仍然有价值A=123
。我在这里做错了什么?
解决方案
在正则表达式中使用括号来捕捉A=
. 捕获的值将可用于match[1]
(match[0]
将是整个表达式)。
function formAnswer() {
let input = document.getElementById('given').value;
match = input.match(/A=(.*)/);
document.getElementById('result').value = match[1];
}
<input type="text" id="given" placeholder="Given"/>
<input type="text" id="result" placeholder="Result"/>
<input type="button" onClick="formAnswer();"/>
推荐阅读
- java - 错误:找到了很久,而需要数组
- android - 由 ResourceNotFoundException 引起的类 NavigationView 膨胀错误
- delphi - 如何从对象存储库中删除表单
- javascript - Javascript中for ... of循环和执行上下文中的解构赋值
- apache-spark - 如何使用 Spark 对象获取 Hive 表的位置值?
- java - 我如何从列中获取价值?(爪哇)
- visual-studio-code - VS Code - 将这些推荐的设置粘贴到您的工作区设置中
- c++ - 如何使用 key2 更新 STL 映射 key1 并将值复制到 key2
- laravel - Laravel 两次加载所有页面
- python - 我如何在 python 中扎根(除平方根)?