Search
There are a few ways to search for strings in JavaScript. Strings has the startsWith
, endsWith
, indexOf
, lastIndexOf
, charAt
, search
and includes
, and match
functions.
startsWith
startsWith
checks if a string starts with the substring you pass in.
For example:
const str = "Hello world.";
const hasHello = str.startsWith("Hello"); // trueconst str2 = "Hello world.";
const hasHello2 = str.startsWith("abc"); // false
endsWith
endsWith
checks if a string ends with the substring you pass in.
For example:
const str = "Hello world.";
const hasHello = str.endsWith("world."); // trueconst str2 = "Hello world.";
const hasHello2 = str.endsWith("abc"); // false
indexOf
indexOf
finds the index of the first occurrence of the substring. Returns -1 if not found.
For example:
const str = "Hello Hello.";
const hasHello = str.indexOf("Hello"); // 0
const hasHello2 = str.indexOf("abc"); // -1
lastIndexOf
lastIndexOf
finds the index of the last occurrence of the substring. Returns -1 if not found.
For example:
const str = "Hello Hello.";
const hasHello = str.lastIndexOf("Hello"); // 6
const hasHello2 = str.lastIndexOf("abc"); // -1
charAt
charAt
returns the character located at the index of the string.
For example:
const str = "Hello";
const res = str.charAt(0); // 'H'
search
search
get the position of the substring passed into the function. It returns -1 if the substring is not found in the string.
Example:
const str = "Hello";
const res = str.search('H'); // 0
includes
includes
checks if the substring passed in is in the string. Returns true
if it is in the string, false otherwise.
const str = "Hello";
const hasH = str.includes('H'); // true
const hasW = str.includes('W'); // false
Replace
The replace()
function included with strings are useful for replacing parts of strings with another. It returns a new string with the string after substring is replace.
Example:
const str = "Hello Bob";
const res = str.replace("Bob", "James"); // 'Hello James'
replace()
can also be used to replace all occurrences of a substring, for example:
const str = "There are 2 chickens in fridge. I will eat chickens today.";
const res = str.replace(/chickens/g, "ducks"); // "There are 2 chickens in fridge. I will eat chickens today."
If the first argument is a regular expression which searches globally, then it will replace all occurrences of the substring.