Ecofg
Ecofg

Reputation: 35

How get only a specific part of a string using a regular expression?

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?

Upvotes: 0

Views: 1285

Answers (2)

vrintle
vrintle

Reputation: 5596

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" />

Upvotes: 1

K&#233;vin Bibollet
K&#233;vin Bibollet

Reputation: 3623

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

Upvotes: 4

Related Questions