Find a character in javascript

String.prototype.indexOf()

The indexOf() method of String values searches this string and returns the index of the first occurrence of the specified substring. It takes an optional starting position and returns the first occurrence of the specified substring at an index greater than or equal to the specified number.

Try it

Syntax

indexOf(searchString) indexOf(searchString, position) 

Parameters

Substring to search for. All values are coerced to strings, so omitting it or passing undefined causes indexOf() to search for the string «undefined» , which is rarely what you want.

The method returns the index of the first occurrence of the specified substring at a position greater than or equal to position , which defaults to 0 . If position is greater than the length of the calling string, the method doesn’t search the calling string at all. If position is less than zero, the method behaves as it would if position were 0 .

  • ‘hello world hello’.indexOf(‘o’, -5) returns 4 — because it causes the method to behave as if the second argument were 0 , and the first occurrence of o at a position greater or equal to 0 is at position 4 .
  • ‘hello world hello’.indexOf(‘world’, 12) returns -1 — because, while it’s true the substring world occurs at index 6 , that position is not greater than or equal to 12 .
  • ‘hello world hello’.indexOf(‘o’, 99) returns -1 — because 99 is greater than the length of hello world hello , which causes the method to not search the string at all.
Читайте также:  Android выполнение java кода

Return value

The index of the first occurrence of searchString found, or -1 if not found.

Return value when using an empty search string

Searching for an empty search string produces strange results. With no second argument, or with a second argument whose value is less than the calling string’s length, the return value is the same as the value of the second argument:

"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 a second argument whose value is greater than or equal to the string’s length, the return 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, the method behaves as if it found an empty string just after the position specified in the second argument. In the latter instance, the method behaves as if it found an empty string at the end of the calling string.

Description

Strings are zero-indexed: The index of a string’s first character is 0 , and the index of a string’s last character is the length of the string minus 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 

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

"Blue Whale".indexOf("blue"); // returns -1 

Checking occurrences

When checking if a specific substring occurs within a string, the correct way to check is test whether the return value is -1 :

"Blue Whale".indexOf("Blue") !== -1; // true; found 'Blue' in 'Blue Whale' "Blue Whale".indexOf("Bloe") !== -1; // false; no 'Bloe' in 'Blue Whale' 

Examples

Using indexOf()

The following example uses indexOf() to locate substrings in the string «Brave new world» .

const str = "Brave new world"; console.log(str.indexOf("w")); // 8 console.log(str.indexOf("new")); // 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")); // 19 console.log(myCapString.indexOf("cheddar")); // -1 

Using 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); // 4 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 28, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

JavaScript, how to find a character in a string

How do you find a character in a string, using JavaScript?

How do you find a character in a string, using JavaScript?

Every string has an includes() method that accepts one (or more) characters.

This method returns true if the string contains the character, and false if not:

'a nice string'.includes('a') //true 'a nice string'.includes('b') //false

If you need to find the exact position of the letter in the string, however, you need to use the indexOf() method:

'a nice string'.indexOf('a') //0 'a nice string'.indexOf('c') //4

If there are more than one occurrence, this method returns the position of the first one it finds, starting from the left.

Источник

How to Check if a String Contains a Character in JavaScript

In this article, we’ll be looking at different ways to quickly check if a string contains a specific character in JavaScript.

1. String includes() Method

To check if a string contains a particular character, we can call the includes() method on the string, passing the character as an argument e.g., str.includes(char). The includes() method returns true if the string contains the character, and false if it doesn’t.

const str = 'Bread and Milk'; const char1 = 'd'; const char2 = 'p'; console.log(str.includes(char1)); // true console.log(str.includes(char2)); // false 

Tip

To perform a case-insensitive check, convert both the string and the character to lowercase before calling includes() on the string.

const str = 'Bread and Milk'; const char = 'D'; console.log(str.toLowerCase().includes(char.toLowerCase())); // true 

2. String indexOf() Method

We can also use the indexOf() method to check if a string contains a particular character. We call the indexOf() method on the string, passing the character as an argument. Then we compare the result with -1 . For example:

const str = 'Bread and Milk'; const char1 = 'd'; const char2 = 'p'; console.log(str.indexOf(char1) > -1); // true console.log(str.indexOf(char2) > -1); // false 

The indexOf() method searches a string for a value and returns the index of the first occurrence of that value. If the value can’t be found, it returns -1 .

const str = 'Bread and Milk'; const char1 = 'd'; const char2 = 'p'; console.log(str.indexOf(char1)); // 4 console.log(str.indexOf(char2)); // -1 

This is why we compare the result of indexOf() with -1 to check if the character is in the string.

3. Regex Matching

We can test the string against regex patterns to determine if it contains a particular character. One way to do this is with the RegExp test() method.

const str = 'Bread and Milk'; console.log(/d/.test(str)); // true console.log(/p/.test(str)); // false 

The test() method searches the string for a match with the regex. It returns true if it finds a match, and false otherwise.

Using regex matching allows us to specify multiple characters to search for in the string easily.

const str = 'Bread and Milk'; // Contains a digit? console.log(/\d/.test(str)); // false // Contains 'r', 'l' or 'c'? console.log(/[rlc]/.test(str)); // true // Contains whitespace? console.log(/\s/.test(str)); // true 

11 Amazing New JavaScript Features in ES13

This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.

Источник

Оцените статью