0

In an input field I have the value A=123 and I need the JavaScript code to get only the 123 part.

This is what I tried so far:

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();"/>

But this still gets the value A=123. What am I doing wrong here?

2
  • 1
    Just an other note: you have no textarea, you only have text inputs. Commented May 13, 2019 at 18:03
  • If there can be digits only and that is the only allowed text you could use anchors to assert the start and the end of the string and capture in a group 1+ digits ^A=(\d+)$ See regex101.com/r/6FuzJR/1 Commented May 13, 2019 at 20:10

2 Answers 2

4

Use parenthesis in your regular expression to catch what's after A=. The caught value will be available with match[1] (match[0] will be the entire expression).

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();"/>

Sign up to request clarification or add additional context in comments.

Comments

1

You can try this regex: (?<=A=).*

It simply searches for a string which is preceded by "A="

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" onClick="formAnswer();" value="Check" />

3 Comments

Hi @JennyO'Reilly, it seems my eyes aren't working. It would be helpful if you will give some more info. (like, error message, input, etc)
Error is due to compatibility of browser as lookbacks are not implemented in all the browsers
Sorry. I deleted the original comment. The error I get in Firefox 66.0.5 (Win64) is this one: SyntaxError: invalid regexp group. As Code Maniac pointed out, regex lookbacks in JavaScript are not supported by most browsers, as you can see here: kangax.github.io/compat-table/es2016plus/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.