const text = 'Hello world! Welcome to the world of JavaScript.'; const pattern = /world/g; const matches = text.match(pattern); console.log(matches); // ['world', 'world']
const text = 'Hello world! Welcome to the world of JavaScript.'; const pattern = /world/g; const matches = text.matchAll(pattern); for (const match of matches) { console.log(match); // ['world', index: 6, input: 'Hello world! Welcome to the world of JavaScript.', groups: undefined] }
3. search()
search() 方法执行匹配搜索,返回匹配项的索引,如果没有匹配,则返回 -1。
语法
1
str.search(regexp)
示例
1 2 3 4
const text = 'Hello world! Welcome to the world of JavaScript.'; const pattern = /world/; const index = text.search(pattern); console.log(index); // 6
const text = 'Hello world! Welcome to the world of JavaScript.'; const pattern = /world/g; const newText = text.replace(pattern, 'universe'); console.log(newText); // 'Hello universe! Welcome to the universe of JavaScript.'
const text = 'Hello world! Welcome to the world of JavaScript.'; const pattern = /world/; const match = pattern.exec(text); if (match) { const index = match.index; const substring = text.slice(index, index + match[0].length); console.log(text.includes(substring)); // true }