首页 > 解决方案 > 如何使用正则表达式仅获取字符串的特定部分?

问题描述

在输入字段中,我有值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。我在这里做错了什么?

标签: javascriptregex

解决方案


在正则表达式中使用括号来捕捉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();"/>


推荐阅读