简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM