Match dynamic string using regex

后端 未结 4 533
旧巷少年郎
旧巷少年郎 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:36

    You're mixing up the two ways of creating regexes in JavaScript. If you use a regex literal, / is the regex delimiter, the g modifier immediately follows the closing delimiter, and \b is the escape sequence for a word boundary:

    var regex = /width\b/g;
    

    If you create it in the form of a string literal for the RegExp constructor, you leave off the regex delimiters, you pass modifiers in the form of a second string argument, and you have to double the backslashes in regex escape sequences:

    var regex = new RegExp('width\\b', 'g');
    

    The way you're doing it, the \b is being converted to a backspace character before it reaches the regex compiler; you have to escape the backslash to get it past JavaScript's string-literal escape-sequence processing. Or use a regex literal.

提交回复
热议问题