skip to Main Content

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


  1. With the match() operator:

    const s = 'String=ajdje782@29sjdjn';
    const [var1, var2] = s.match(/d+/g);
    console.log(`var1=${var1} var2=${var2}`); 

    The regular expression matches as follows:

    Node Explanation
    d+ digits (0-9) (1 or more times (matching the most amount possible))

    The g modifiers in //g meant all matches.

    Login or Signup to reply.
  2. const string = "ajdje782@29sjdjn";
    
    // Define a regular expression pattern to match the numbers before and after the symbol
    const pattern = /(d+)@(d+)/;
    
    // Use the match() function to find the match
    const match = string.match(pattern);
    
    if (match) {
      // Extract the numbers before and after the symbol
      const numberBefore = parseInt(match[1], 10);
      const numberAfter = parseInt(match[2], 10);
      
      console.log("Number before:", numberBefore);
      console.log("Number after:", numberAfter);
    } else {
      console.log("No match found.");
    }
    

    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.

    Login or Signup to reply.
  3. 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 number
    D – any non-digit separator
    (d+) – capture the second number
    .slice(1) – get only the captured numbers (skip the whole match string)

    const str = 'ajdje782@29sjdjn';
    
    const [num1, num2] = str.match(/(d+)D(d+)/)?.slice(1) || [];
    
    console.log(num1, num2);

    If the format is already validated you could just extract 2 numbers from the string:

    const str = 'ajdje782@29sjdjn';
    
    const [num1, num2] = str.match(/d+/g);
    
    console.log(num1, num2);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search