// 示例代码:使用 lastIndex 属性
// 创建一个正则表达式对象,设置为全局匹配 (g)
let regex = /test/g;
let str = "This is a test string with another test";
// 使用 lastIndex 属性来跟踪上次匹配的位置
console.log(regex.lastIndex); // 输出: 0 (初始值)
// 使用 exec 方法进行匹配
let match = regex.exec(str);
console.log(match); // 输出: ["test"]
console.log(regex.lastIndex); // 输出: 14 (上一次匹配的结束位置)
// 再次调用 exec 方法继续匹配
match = regex.exec(str);
console.log(match); // 输出: ["test"]
console.log(regex.lastIndex); // 输出: 37 (第二次匹配的结束位置)
// 如果没有更多匹配,lastIndex 将重置为 0
match = regex.exec(str);
console.log(match); // 输出: null
console.log(regex.lastIndex); // 输出: 0
lastIndex 是正则表达式对象的一个属性,主要用于全局 (g) 或粘性 (y) 模式的正则表达式。它表示下一次匹配的起始位置。exec() 方法时,lastIndex 会更新为当前匹配的结束位置(即匹配字符串之后的第一个字符位置)。lastIndex 会重置为 0。上一篇:js findindex
下一篇:js tofixed
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站