How to filter a string in js?

  • 0
    I have several lines
    And I need to split them into words that are in parentheses and outside the parentheses.
    Like this
    var val1 = '111[red]car';
    var val2 = 'ms,d[green][black]tea';
    var val3 = 'asdsasun'
    alert({'in': val1.replace(/[^[...]]/g, "")   ,' out': val1.replace(/[[...]]/g, "");    }); // {'in':[ red  ]   ,'out':[ 111,   car]    }
    alert({'in': val2.replace(/[^[...]]/g, "")   ,' out': val2.replace(/[[...]]/g, "");    }) // {'in':[ green,  black ]   ,'out':[ms,d, tea ]    }
    alert({'in': val3.replace(/[^[...]]/g, "")   ,' out': val3.replace(/[[...]]/g, "");    })  // val1

    How can I best do this?
    JavaScript Lilah Middleton, Jul 13, 2020

  • 1 Answers
  • 0
    {
    in: str.match(/(?<=\[).+?(?=\])/g),
    out: str.match(/(?<=^|\])[^\[]+/g),
    }
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!