I’m trying to get the number that is before a symbol and the number after the symbol.
Example:
String=ajdje782@29sjdjn
I want a variable with the number 782
and a variable with 29
.
The numbers can be any length and there can be any number of letters. The symbol may be between 3 or 4 different symbols.
I tried using for loops to find the start and end of each side and store them, but it got too complicated and I couldn’t understand it
3
Answers
With the
match()
operator:The regular expression matches as follows:
d+
The
g
modifiers in//g
meant all matches.In this JavaScript code, the regular expression /(d+)@(d+)/ captures two sets of digits separated by the "@" symbol. The match() function returns an array containing the entire matched string as the first element, followed by the captured groups.
You can adjust the regular expression according to the symbols you expect in your input string. The captured numbers are then converted to integers using parseInt().
Remember that the specific symbols you want to match should be added within the regular expression. You can modify the regular expression pattern to account for different symbols as needed.
It’s not very clear what are all possible input formats, but if you want only 2 numbers separated by a non-digit separator (that implies you want to validate the format also):
(d+)
– capture the first numberD
– any non-digit separator(d+)
– capture the second number.slice(1)
– get only the captured numbers (skip the whole match string)If the format is already validated you could just extract 2 numbers from the string: