JavaScript RegExp objects

前端 未结 5 1303
情话喂你
情话喂你 2020-12-07 03:51

I try to write a simple Markdown parser in JavaScript. Therefore I want to check for the [link content][link id] syntax. I use the following code:



        
相关标签:
5条回答
  • 2020-12-07 04:10

    Double escape you backslashes:

    var r = new RegExp( '\\[(.*?)\\][ ]*\[([0-9]+)\\]', 'g' );
    
    0 讨论(0)
  • 2020-12-07 04:13

    In addition to the pattern's backslash problem, this:

    data = data.replace( r, '<a href="$2">$1</a>' );
    

    could be dangerous. I'll assume you've already taken care of the HTML-escaping, so I won't be able to do this:

    [<script>stealCookies()</script>][http://oops.example.com/]
    [hover me][http://hello" onmouseover="stealCookies()]
    

    but you'll still need to check the URL is a known-good scheme so I can't do this:

    [click me][javascript:stealCookies()]
    

    You'll probably want to use the String.replace(r, func) variant of the method, and include validation in your replacement-making 'func'.

    0 讨论(0)
  • 2020-12-07 04:13
    var r = /\[(.*?)\][ ]*\[([0-9]+)\]/g;
    data = data.replace( r, '<a href="$2">$1</a>' );
    
    0 讨论(0)
  • 2020-12-07 04:24

    Because the first argument of the RegExp constructor is a string, not a pattern literal, you have to escape the backslashes, since you want literal backslashes in the pattern:

    var r = new RegExp( '\\[(.*?)\\][ ]*\\[([0-9]+)\\]', 'g' );
    
    0 讨论(0)
  • 2020-12-07 04:27

    You need to double escape:

    var r = new RegExp( '\\[(.*?)\\][ ]*\\[([0-9]+)\\]', 'g' )
    
    0 讨论(0)
提交回复
热议问题