skip to Main Content

I have a string like this:
124:111,120:444,103:504,494:120,404:111,200:100,

I will use replace() and let’s say I want to select
124:111,120:444,103:504,494:120,404:111,**200:100,**
without actually defining 200:100, but instead having it to work like this:

Define only :100, regex selects everything to the left until "," approaches and everything to the right including first "," => 200:100,

Is it possible to have such a regex? Thanks for any information

2

Answers


  1. Without using replace() you could do it this way in my opinion.

    1. Define the regex pattern and matches any sequence of characters that does not include a comma

      const pattern = /[^,]*:100,/;
      
    2. Use match() to find a match of the pattern in the input string:

      const match = string.match(pattern);
      
    3. Check if a match is found

      if (match) {
       const result = match[0];
        console.log(result);
      } else {
        console.log("Pattern not found");
      }
      
    Login or Signup to reply.
  2. Regex

    ,?(d*?):100
    

    Will match :100 and capture the digits before that:

    const regex = /,?(d*?):100/gm;
    const sourceValue = '124:111,120:444,103:504,494:120,404:111,200:100,';
    const match = regex.exec(sourceValue);
    
    console.log(match[1]);
    // 200

    split()

    Another option is to split on ,, then check if the right side has the value you’re searching for

    const sourceValue = '124:111,120:444,103:504,494:120,404:111,200:100,';
    const searchValue = 100;
    
    sourceValue.split(',').forEach(p => {
        const [ l, r ] = p.split(':');
        if (+r === searchValue) {
            console.log(`Found searchValuennLefttt${l}nRighttt${r}nOriginalt${p}`);
        }
    });
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search