How to use JavaScript regex over multiple lines?

前端 未结 6 994
情歌与酒
情歌与酒 2020-11-22 04:04
var ss= \"
aaaa\\nbbb\\nccc
ffffd\"; var arr= ss.match( //gm ); alert(arr); // null

I\'d want the PR

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 04:36

    DON'T use (.|[\r\n]) instead of . for multiline matching.

    DO use [\s\S] instead of . for multiline matching

    Also, avoid greediness where not needed by using *? or +? quantifier instead of * or +. This can have a huge performance impact.

    See the benchmark I have made: http://jsperf.com/javascript-multiline-regexp-workarounds

    Using [^]: fastest
    Using [\s\S]: 0.83% slower
    Using (.|\r|\n): 96% slower
    Using (.|[\r\n]): 96% slower
    

    NB: You can also use [^] but it is deprecated in the below comment.

提交回复
热议问题