Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Learn String Search



JavaScript String Search


In JavaScript, you can search for substrings within a string using various methods. Here are some common approaches:

  1. indexOf(searchValue[, fromIndex]): Returns the index of the first occurrence of a specified substring within a string. If the substring is not found, it returns -1.

  2. let str = "Hello, world!";
    console.log(str.indexOf("world")); // Output: 7


  3. lastIndexOf(searchValue[, fromIndex]): Returns the index of the last occurrence of a specified substring within a string, searching backward from the specified index.

  4. let str = "Hello, world!";
    console.log(str.lastIndexOf("o")); // Output: 8


  5. includes(searchString[, position]): Checks whether a string contains a specified substring. It returns true if the substring is found, otherwise false.

  6. let str = "Hello, world!";
    console.log(str.includes("world")); // Output: true


  7. startsWith(searchString[, position]): Checks whether a string starts with a specified substring. It returns true if the string starts with the specified substring, otherwise false.

  8. let str = "Hello, world!";
    console.log(str.startsWith("Hello")); // Output: true


  9. endsWith(searchString[, length]): Checks whether a string ends with a specified substring. It returns true if the string ends with the specified substring, otherwise false.

  10. let str = "Hello, world!";
    console.log(str.endsWith("world!")); // Output: true


  11. RegExp: Regular expressions can be used for more advanced string searches, allowing for pattern matching and more complex search criteria.

  12. let str = "Hello, world!";
    let pattern = /world/g;
    console.log(str.match(pattern)); // Output: ["world"]


    Each of these methods provides different ways to search for substrings within a string, offering flexibility based on your specific search requirements.





Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java