Converting user input string to regular expression

前端 未结 11 1999
无人及你
无人及你 2020-11-22 14:18

I am designing a regular expression tester in HTML and JavaScript. The user will enter a regex, a string, and choose the function they want to test with (e.g. search, match,

11条回答
  •  半阙折子戏
    2020-11-22 14:30

    In my case the user input somethimes was sorrounded by delimiters and sometimes not. therefore I added another case..

    var regParts = inputstring.match(/^\/(.*?)\/([gim]*)$/);
    if (regParts) {
        // the parsed pattern had delimiters and modifiers. handle them. 
        var regexp = new RegExp(regParts[1], regParts[2]);
    } else {
        // we got pattern string without delimiters
        var regexp = new RegExp(inputstring);
    }
    

提交回复
热议问题