且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JS中正则表达式中插入符号(^)和美元符号($)的需求是什么?

更新时间:2023-02-22 13:45:05

Javascript RegExp()允许您指定多行模式(m),它改变 ^ $ 的行为。

Javascript RegExp() allows you to specify a multi-line mode (m) which changes the behavior of ^ and $.

^ 表示多行模式下当前行的开头,否则字符串的开头

^ represents the start of the current line in multi-line mode, otherwise the start of the string

$ 表示多行模式下当前行的结尾,否则字符串的结尾

$ represents the end of the current line in multi-line mode, otherwise the end of the string

例如:这允许您在下一行以var开头的行的末尾匹配分号之类的内容 /; $ \ n \ * * var / m

For example: this allows you to match something like semicolons at the end of a line where the next line starts with "var" /;$\n\s*var/m

快速regexen还需要一个锚点点,某处开始搜索字符串中的某个地方。这些字符告诉Regex引擎从哪里开始查看并且通常会减少回溯的数量,在许多情况下使你的Regex 更快,更快

Fast regexen also need an "anchor" point, somewhere to start it's search somewhere in the string. These characters tell the Regex engine where to start looking and generally reduce the number of backtracks, making your Regex much, much faster in many cases.

注意:这些知识来自Nicolas Zakas的高性能Javascript

NOTE: This knowledge came from Nicolas Zakas's High Performance Javascript

结论:你应该使用它们!