当前位置:嗨网首页>书籍在线阅读

19-锚点

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

17.17 锚点

通常,大家会关心一个字符串的开始和结束,或者整个字符串(而不只是一部分),这时候锚点就派上用场了。有两种锚点,分别是用于匹配行开始的^,以及用于匹配行结束的$。

const input = "It was the best of times, it was the worst of times";
const beginning = input.match(/^\w+/g);   // "It"
const end = input.match(/\w+$/g);         // "times"
const everything = input.match(/^.*$/g);  // 跟输入一样
const nomatch1 = input.match(/^best/ig);
const nomatch2 = input.match(/worst$/ig);

关于锚点,有个细节需要知道。一般情况下,它们匹配的是整个字符串的开始和末尾,即使字符串中有换行。如果想把某个字符串当做多行字符串(以换行符分隔)来处理,就需要用到m(多行)选项:

const input = "One line\nTwo lines\nThree lines\nFour";
const beginnings = input.match(/^\w+/mg);  // ["One", "Two", "Three", "Four"]
const endings = input.match(/\w+$/mg);     // ["line", "lines", "lines", "Four"]