indexOf() 方法返回索引在调用 String 对象对于指定值的首次出现,开始搜索从 fromIndex 。返回 -1 若未找到值。

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. 注意: 对于数组方法,见 Array.prototype.indexOf() .

句法

str.indexOf(searchValue [, fromIndex])
					

参数

searchValue

要搜索的字符串值。

If no string is explicitly provided, searchValue will be coerced to " undefined " , and this value will be searched for in str .

So, for example: 'undefined'.indexOf() will return 0 , as undefined is found at position 0 in the string undefined . 'undefine'.indexOf() however will return -1 , as undefined is not found in the string undefine .

fromIndex 可选

An integer representing the index at which to start the search. Defaults to 0 .

For fromIndex values lower than 0 , or greater than str .length , the search starts at index 0 and str .length , respectively.

例如, 'hello world'.indexOf('o', -5) will return 4 , as it starts at position 0 ,和 o is found at position 4 . On the other hand, 'hello world'.indexOf('o', 11) (and with any fromIndex value greater than 11 ) will return -1 , as the search is started at position 11 , a position after the end of the string.

返回值

The index of the first occurrence of searchValue ,或 -1 若找不到。

An empty string searchValue produces strange results. With no fromIndex value, or any fromIndex value lower than the string's length , the returned value is the same as the fromIndex 值:

'hello world'.indexOf('') // returns 0
'hello world'.indexOf('', 0) // returns 0
'hello world'.indexOf('', 3) // returns 3
'hello world'.indexOf('', 8) // returns 8
					

However, with any fromIndex value equal to or greater than the string's length , the returned value is the string's length :

'hello world'.indexOf('', 11) // returns 11
'hello world'.indexOf('', 13) // returns 11
'hello world'.indexOf('', 22) // returns 11
					

In the former instance, JS seems to find an empty string just after the specified index value. In the latter instance, JS seems to be finding an empty string at the end of the searched string.

描述

Characters in a string are indexed from left to right. The index of the first character is 0 , and the index of the last character of a string called stringName is stringName .length - 1 .

'Blue Whale'.indexOf('Blue')      // returns  0
'Blue Whale'.indexOf('Blute')     // returns -1
'Blue Whale'.indexOf('Whale', 0)  // returns  5
'Blue Whale'.indexOf('Whale', 5)  // returns  5
'Blue Whale'.indexOf('Whale', 7)  // returns -1
'Blue Whale'.indexOf('')          // returns  0
'Blue Whale'.indexOf('', 9)       // returns  9
'Blue Whale'.indexOf('', 10)      // returns 10
'Blue Whale'.indexOf('', 11)      // returns 10
					

indexOf() method is case sensitive. For example, the following expression returns -1 :

'Blue Whale'.indexOf('blue')  // returns -1
					

校验出现

注意, 0 doesn't evaluate to true and -1 doesn't evaluate to false . Therefore, when checking if a specific string exists within another string, the correct way to check would be:

'Blue Whale'.indexOf('Blue') !== -1  // true
'Blue Whale'.indexOf('Bloe') !== -1  // false
~('Blue Whale'.indexOf('Bloe')) // 0, which is falsy
					

范例

使用 indexOf()

以下范例使用 indexOf() to locate values in the string "Brave new world" .

const str = 'Brave new world'
console.log('Index of first w from start is ' + str.indexOf('w'))   // logs 8
console.log('Index of "new" from start is ' + str.indexOf('new'))   // logs 6
					

indexOf() and case-sensitivity

The following example defines two string variables.

The variables contain the same string, except that the second string contains uppercase letters. The first console.log() method displays 19 . But because the indexOf() method is case sensitive, the string " cheddar " is not found in myCapString , so the second console.log() method displays -1 .

const myString    = 'brie, pepper jack, cheddar'
const myCapString = 'Brie, Pepper Jack, Cheddar'
console.log('myString.indexOf("cheddar") is ' + myString.indexOf('cheddar'))
// logs 19
console.log('myCapString.indexOf("cheddar") is ' + myCapString.indexOf('cheddar'))
// logs -1
					

使用 indexOf() to count occurrences of a letter in a string

The following example sets count to the number of occurrences of the letter e in the string str :

const str = 'To be, or not to be, that is the question.'
let count = 0
let position = str.indexOf('e')
while (position !== -1) {
  count++
  position = str.indexOf('e', position + 1)
}
console.log(count)  // displays 4
					

规范

规范
ECMAScript (ECMA-262)
在该规范中的 String.prototype.indexOf 定义。

浏览器兼容性

The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
indexOf Chrome 1 Edge 12 Firefox 1 IE 3 Opera 3 Safari 1 WebView Android 1 Chrome Android 18 Firefox Android 4 Opera Android 10.1 Safari iOS 1 Samsung Internet Android 1.0 nodejs 0.1.100

图例

完整支持

完整支持

另请参阅

元数据

  • 最后修改:
  1. 标准内置对象
  2. String
  3. 特性
    1. String 长度
  4. 方法
    1. String.fromCharCode()
    2. String.fromCodePoint()
    3. String.prototype.anchor()
    4. String.prototype.big()
    5. String.prototype.blink()
    6. String.prototype.bold()
    7. String.prototype.charAt()
    8. String.prototype.charCodeAt()
    9. String.prototype.codePointAt()
    10. String.prototype.concat()
    11. String.prototype.endsWith()
    12. String.prototype.fixed()
    13. String.prototype.fontcolor()
    14. String.prototype.fontsize()
    15. String.prototype.includes()
    16. String.prototype.indexOf()
    17. String.prototype.italics()
    18. String.prototype.lastIndexOf()
    19. String.prototype.link()
    20. String.prototype.localeCompare()
    21. String.prototype.match()
    22. String.prototype.matchAll()
    23. String.prototype.normalize()
    24. String.prototype.padEnd()
    25. String.prototype.padStart()
    26. String.prototype.repeat()
    27. String.prototype.replace()
    28. String.prototype.replaceAll()
    29. String.prototype.search()
    30. String.prototype.slice()
    31. String.prototype.small()
    32. String.prototype.split()
    33. String.prototype.startsWith()
    34. String.prototype.strike()
    35. String.prototype.sub()
    36. String.prototype.substr()
    37. String.prototype.substring()
    38. String.prototype.sup()
    39. String.prototype.toLocaleLowerCase()
    40. String.prototype.toLocaleUpperCase()
    41. String.prototype.toLowerCase()
    42. String.prototype.toSource()
    43. String.prototype.toString()
    44. String.prototype.toUpperCase()
    45. String.prototype.trim()
    46. String.prototype.trimEnd()
    47. String.prototype.trimStart()
    48. String.prototype.valueOf()
    49. String.prototype[@@iterator]()
    50. String.raw()
  5. 继承:
  6. Function
  7. 特性
    1. Function.arguments
    2. Function.caller
    3. Function.displayName
    4. Function.length
    5. Function.name
  8. 方法
    1. Function.prototype.apply()
    2. Function.prototype.bind()
    3. Function.prototype.call()
    4. Function.prototype.toSource()
    5. Function.prototype.toString()
  9. Object
  10. 特性
    1. Object.prototype.__proto__
    2. Object.prototype.constructor
  11. 方法
    1. Object.prototype.__defineGetter__()
    2. Object.prototype.__defineSetter__()
    3. Object.prototype.__lookupGetter__()
    4. Object.prototype.__lookupSetter__()
    5. Object.prototype.hasOwnProperty()
    6. Object.prototype.isPrototypeOf()
    7. Object.prototype.propertyIsEnumerable()
    8. Object.prototype.toLocaleString()
    9. Object.prototype.toSource()
    10. Object.prototype.toString()
    11. Object.prototype.valueOf()
    12. Object.setPrototypeOf()