Match dynamic string using regex

后端 未结 4 543
旧巷少年郎
旧巷少年郎 2020-12-02 00:26

I\'m trying to detect an occurrence of a string within string. But the code below always returns \"null\". Obviously something went wrong, but since I\'m a newbie, I can\'t

4条回答
  •  天涯浪人
    2020-12-02 00:54

    Notice that '\\b' is a single slash in a string followed by the letter 'b', '\b' is the escape code \b, which doesn't exist, and collapses to 'b'.

    Also consider escaping metacharacters in the string if you intend them to only match their literal values.

    var string = 'width';
    var quotemeta_string = string.replace(/[^$\[\]+*?.(){}\\|]/g, '\\$1'); // escape meta chars
    var pattern = quotemeta_string + '\\b';
    var re = new RegExp(pattern);
    var bool_match = re.test(input); // just test whether matches
    var list_matches = input.match(re); // get captured results
    

提交回复
热议问题