• Home
  • JavaScript
  • How to check if string contains substring in javascript

How to check if string contains substring in javascript



Depending on what you currently want to achieve, you can use several solutions to check if the string contains substring:

1. includes();

This method will work if you need to know if substring occurs in the string or not. String.includes () returns true or false.

let string = 'Ala ma kota, a baba Jaga cukierki';

console.log(string.includes('kota'));       // true
console.log(string.includes('worek'));      // false


2. substring();

This method will work if you want to return some part of the string. You must indicate substring start and end place. If you do not indicate the end point, the rest of the string will be returned.

let string = 'Ala ma kota, a baba Jaga cukierki';

console.log(string.substring(0, 11));       // "Ala ma kota"
console.log(string.substring(15));          // "baba Jaga cukierki"


3. match();

The match() method checks if the given condition is reflected in the string. For example, you can return all uppercase letters from text:

let string = 'Ala ma kota, a baba Jaga cukierki',
    regex = /[A-Z]/g;

console.log(string.match(regex));       // ["A", "J"]


4. indexOf();

This method will check where the substring begins in the string. In the first case we check the index for the first occurrence of the word “cat” (for a black cat), and in the second for the second (white) “cat”.

let string = 'Ala ma czarnego kota, a baba Jaga cukierki i białego kota',

console.log(string.indexOf('kota'));       // 16 
console.log(string.indexOf('kota', string.indexOf('kota') +  1));       // 53


Joanna

Leave a Reply

Your email address will not be published. Required fields are marked *