Javascript RegExp and boundaries

前端 未结 5 587
北恋
北恋 2021-01-15 16:48

A colleague asked me about a Regular expression problem, and I can\'t seem to find and answer for him.

We\'re using boundaries to highlight certain lengths of text i

5条回答
  •  离开以前
    2021-01-15 17:13

    In fact you have to backslash everything in the string passed to the RegExp constructor :

    var re = /my_([\w_]+-\d-)regexp/
    

    is equivalent to :

    var re = new RegExp("my_\(\[\\\w_\]+-\\\d-\)regexp")
    

    And both match the following stupid example :

    "my_very_obvious-4-regexp".match(re)
    ["my_very_obvious-4-regexp", "very_obvious-4-"]
    

提交回复
热议问题