skip to Main Content

I need reg expression.
I do calculator, and this string appear at my view side of app.
How to get this “111+22-33*4” from this “111+++22-33*****4”

Or another example
How to get “22243+11” from “22243++++11”

“565656565656565656565”

2

Answers


  1. Here’s how to do this with a simple loop.

    function strip(s) {
        var out = "";
        var last = 'X';
        for( let i = 0; i < s.length; i++ )
        {
            const c = s[i];
            if( "+-*/".indexOf(c) < 0 || c != last )
            {
                out = out + c;
            }
            last = c;
        }
        return out;
    }
    
    console.log( strip("2222++++444"));
    console.log( strip("111+++222***333///444+-5"));
    Login or Signup to reply.
  2. console.log('+-111+++22-33*****4//////3'.replace(/([-/*+])1+/g, '$1'));

    Analysis:

    ([-/*+]) – capture your target character to replace into a capture group
    1+ – match any number of repeating captured character
    /g – global replace
    $1 – replace with 1 captured character

    An Array::reduce() one-liner:

    const str = '+-111+++22-33*****4//////3';
    
    const res = str.split('').reduce((r,c,i,arr) => i && arr[i-1] === c && '*/+-'.includes(c) ? r : r + c, '');
    
    console.log(res);

    And a benchmark:

    enter image description here

    <script benchmark data-count="1000000">
    
    const str = '+-111+++22-33*****4//////3';
    
    // @benchmark Tim
    function strip(s) {
        var out = "";
        var last = 'X';
        for( let i = 0; i < s.length; i++ )
        {
            const c = s[i];
            if( "+-*/".indexOf(c) < 0 || c != last )
            {
                out = out + c;
            }
            last = c;
        }
        return out;
    }
    //@run
    strip(str)
    
    // @benchmark regexp
    str.replace(/([-/*+])1+/g, '$1');
    
    // @benchmark Array::reduce()
    str.split('').reduce((r,c,i,arr) => i && arr[i-1] === c && '*/+-'.includes(c) ? r : r + c, '');
    
    </script>
    <script src="https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js"></script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search