Strings are a sequence of zero or more characters written inside quotes used to represent text.
Strings may consist of letters, numbers, symbols, words, or sentences.
Strings are immutable, they cannot be changed.
Each character in a string has an index.
The first character will be index 0 the second character will be index 1 and so on.
There are two ways to access an individual character in a string.
charAt() method
const str1 = "abc"; string
str1.charAt(0); character at index 0 → "a"
str1.charAt(1); character at index 1 → "b"
str1.charAt(2); character at index 2 → "c"
str1.charAt(3); character at index 3 → "" index not found
Alternatively use at() or slice() methods
bracket notation []
const str2 = "abc"; string
str2[0]; character at index 0 → "a"
str2[1]; character at index 1 → "b"
str2[2]; character at index 2 → "c"
str2[3]; character at index 3 → undefined index not found
Check if a string contains another string using the includes() method.
includes() method returns true if a string contains a specified value, otherwise, it returns false
const str3 = "Hello World";
str3.includes("e"); returns boolean ↴
true → "e" found in string
const str4 = "Hello World";
str4.includes("a"); returns boolean ↴
false → "a" NOT found in string
Initialize a variable to hold the string to check if it contains another string.
const string1 = "hello big world"; → user input
Initialize a variable to hold the substring to check if it is within the string.
const string2 = "big"; → user input
Define a function containsSubstring to check if a string contains another string
function containsSubstring(str, substring) {}
The function takes two strings as input str and substring and returns true if substring found in string, otherwise returns false.
includes method checks if a substring exists within a string.
return str.includes(substring)
If includes() returns true then the substring has been found in the string.
If includes() returns false then the substring has NOT been found in the string.
If the function returns true, substring found in the string ✔
If the function returns false, substring not found in the string ✖
Call the function with ↴
containsSubstring(string1, string2);
Check if a string contains another string.
const string1 = "hello big world";
const string2 = "big";
function containsSubstring(str, substring) {
return str.includes(substring);
}
call function
containsSubstring(string1, string2); returns ↴
true