在 JavaScript 中,可以使用以下方法检索关键字:
- indexOf():返回指定关键字在字符串中首次出现的位置,如果没有找到则返回 -1。例如:
var str = "This is a sample string."; var keyword = "sample"; var index = str.indexOf(keyword); console.log(index); // 输出:10
- includes():检查字符串是否包含指定关键字,返回布尔值。例如:
var str = "This is a sample string."; var keyword = "sample"; var hasKeyword = str.includes(keyword); console.log(hasKeyword); // 输出:true
- search():返回指定关键字首次出现的位置,如果没有找到则返回 -1。与 indexOf() 类似,但支持使用正则表达式作为关键字。例如:
var str = "This is a sample string."; var keyword = /sample/; var index = str.search(keyword); console.log(index); // 输出:10
- match():返回包含指定关键字的数组,如果没有找到则返回 null。同样支持正则表达式作为关键字。例如:
var str = "This is a sample string."; var keyword = /sample/; var matches = str.match(keyword); console.log(matches); // 输出:["sample"]
这些方法可以用于字符串中的关键字检索,你可以根据具体需求选择适合的方法。