Table of contents
- JavaScript Strings: In Depth
- String Properties and Methods:
- 1. length:
- 2. charAt():
- 3. charCodeAt():
- 4. indexOf():
- 5. lastIndexOf():
- 6. includes():
- 7. startsWith():
- 8. endsWith():
- Note:
- 9. toUpperCase():
- 10. toLowerCase():
- 11. substring():
- 12. trim():
- 13. slice():
- Note:
- 14. split():
- 15. padStart() & padEnd():
- Note:
- 16. search():
- 17. match():
- 18. matchAll():
- Note:
- 19. replace() & replaceAll():
- Note:
- 20. concat():
- Note:
- Instead/Alternative of concat()
JavaScript Strings: In Depth
JavaScript strings are sequences of characters used to represent text, numbers, or any symbol. They are fundamental building blocks for web development and are manipulated frequently.
Here's a deep dive into JavaScript strings, covering their details and methods with examples:
String Creation and Representation:
Single Quotes (' '):
Strings can be created using single quotes. For Example:
// Single Quotes string representation
let myName = 'Muhammad Bilal'; // Single Quotes
console.log(myName); // Output: Muhammad Bilal
Double quotes (""):
Strings can also be created using double quotes. For Example:
// Double Quotes string representation
let myName = "Muhammad Bilal"; // Double Quotes
console.log(myName); // Output: Muhammad Bilal
Backticks (` `):
Backticks allow for template literals with embedded expressions${expression}
. It allows multi-line strings and string interpolation. Here are some examples:
// Backticks representation
let myName = "Muhammad Bilal";
let welcome = `Welcome, ${myName}`;
console.log(welcome); // Output: Welcome, Muhammad Bilal
Benefits of Using Backticks:
Example of multi-line string and string interpolation without backticks:
let a = 10;
let b = 20;
console.log("The output is : " + (a + b) + " Here it is...");
// Output is: The output is : 30 Here it is...
// This output is in the single line
// if we want to make it multi-line then we need to put " \n " into it
// For Example
console.log("The output is :" + (a + b) + "\nHere it is");
// Now the Output is:
// The output is : 30
// Here it is
Example of multi-line string and string interpolation with backticks:
It is a modern, readable, and reliable method.
let a = 10;
let b = 20;
console.log(`The output is : ${a + b} Here it is...`);
// Output is: The output is: 30 Here it is...
// This output is in the single line if we want to make it multi-line then
console.log(`The output is : ${a + b}
Here it is...`);
// Now the Output is:
// The output is : 30
// Here it is
So you can see how easy it is with the implementation of backticks.
String Properties and Methods:
In JavaScript, strings are objects, and they have several properties and methods. In this article, we will discuss all of the string properties in detail.
1. length:
The length
property of a string returns the number of characters present in the string. For Example:
let str = "Muhammad Bilal";
console.log(str.length);
// Output: 14
// If you count the variable Muhammad Bilal it has the length of 13 but
// it counts space or a gap between Muhammad and Bilal as a
// character number so it prints 14
2. charAt():
The charAt()
method of a string returns the character at a specified index. The index is given within the small brackets (). The index is zero-based, so the first character in the string is at index 0. For Example:
let str = "Muhammad Bilal";
console.log(str.charAt(2)); // Here 2 is the index,
// as Index is start from 0 so result is h
// Output: h
3. charCodeAt():
The charCodeAt()
method of a string returns the Unicode code point of the character at a specified index. The index is given within the small brackets ().
For Example:
let uniCode = "Muhammad Bilal";
console.log(uniCode.charCodeAt(0)); // Here 0 is the index,
// as Index is start from 0 so
// Output: 77 // ---> // It is unicode of M
4. indexOf():
TheindexOf()
method of a string returns the index of the first occurrence of a substring within the string. This method finds character from the last. It is just the opposite to charAt()
which takes a character as input and returns the index of the string while indexOf()
takes substrings or characters as input and returns index as an output.
For Example:
let inStr = "Muhammad Bilal";
console.log(inStr.indexOf("d"));
// Here d is the character of a string as input
// Output: 7
let inStr = "Welcome to my blog";
console.log(inStr.indexOf("to"));
// You can search more than obe character or a word
// Output: 8
5. lastIndexOf():
ThelastIndexOf()
method of a string returns the index of the last occurrence of a substring within the string. This method finds character present in the last. This method returns-1
if no values are found there.
For Example:
let inStr = "Muhammad Bilal is the owner of these blogs";
console.log(inStr.lastIndexOf("o"));
// Outpu: 39
// It finds the o present at last mean it takes o from blog
6. includes():
Theincludes()
method of a string returns true if the substring is found within the string; otherwise, it returns false.
For Example:
Example 1:
let inStr1 = "MBilal write blogs";
console.log(inStr1.includes("o"));
// Outpu: true
Example 2:
let inStr2 = "MBilal write blogs";
console.log(inStr2.includes("u"));
// Outpu: false
7. startsWith():
ThestartsWith()
method of a string determines whether a string starts with the characters of a specified string, returning true or false.
For Example:
let inStr2 = "MBilal write blogs";
console.log(inStr2.startsWith("B"));
// Outpu: false // Because it does't start with B
8. endsWith():
TheendsWith()
method of a string determines whether a string ends with the characters of a specified string, returning true or false.
For Example:
let inStr2 = "MBilal write blogs";
console.log(inStr2.endsWith("gs"));
// Outpu: true
Note:
All of these string methods that are used for searching are case-sensitive.
9. toUpperCase():
ThetoUpperCase()
method of a string converts all the characters to upper case.
For Example:
let str = "my name";
console.log(str.toUpperCase());
Output: MY NAME
10. toLowerCase():
ThetoLowerCase()
method of a string converts all the characters to lowercase.
For Example:
let str = "My Name";
console.log(str.toLowerCase());
Output: my nam
11. substring():
Thesubstring()
method of a string extracts a substring from the string. It takes two parameters. start parameter
and end parameter.
The start parameter specifies the starting index for the extraction, and the end parameter specifies the ending index (the second parameter is not included).
For Example:
let str = "Muhammad Bilal";
console.log(str.substring(2, 6));
Output: hamm // the second parameter 6 is not icluded
12. trim():
The trim()
method of a string removes all the extra spaces from the start and end. More values like trimStart()
removing spaces from the start only and trimEnd()
removing spaces from the end of the string only. But we use trim() removing spaces from the start and end both.
For Example:
let str = " Muhammad Bilal ";
console.log(str);
Output: Muhammad Bilal
console.log(str.trim());
Output: Muhammad Bilal
let strStart = " Muhammad Bilal ";
console.log(strStart.trimStart()); // Remove spaces from the start
Output: Muhammad Bilal
let strEnd = " Muhammad Bilal ";
console.log(strEnd.trimEnd()); // Remove spaces from the end
Output: Muhammad Bilal
13. slice():
The slice()
method of a string extracts a portion from the string. It takes two parameters. start parameter
and end parameter.
The start parameter specifies the starting index for the extraction, and the end parameter specifies the ending index (the second parameter is not included). It is just like the substring()
but the difference is that it can accept negative values.
For Example:
let str = "Muhammad Bilal";
console.log(str.slice(2, 5));
Output: ham
// Here it accept negative value
let str = "Bilal";
console.log(str.slice(-2));
Output: al
Note:
We mostly used slice()
instead of substring().
14. split():
The split()
method is a built-in method of the String object in JavaScript that splits a string into an array of substrings. It takes a separator argument, which is the character or string that the string will be split on. If no separator argument is provided, the string is split on whitespace characters.
For Example:
let str1 = "This blog is owned by Muhammad Bilal";
console.log(str1.split(" "));
Output: [ 'This', 'blog', 'is', 'owned', 'by', 'Muhammad', 'Bilal' ];
let str = "This blog is owned by Muhammad Bilal";
console.log(str.split(" ", 4)); // Optional parameter limit
Output: [ 'This', 'blog', 'is', 'owned' ];
let str2 = "This blog is Blog";
console.log(str2.split(""));
// Without any space prints individual character
// Output:
[
'T', 'h', 'i', 's', ' ',
'b', 'l', 'o', 'g', ' ',
'i', 's', ' ', 'B', 'l',
'o', 'g'
]
let str3 = "This blog is owned by Muhammad Bilal";
console.log(str3.split()); // Without any separator or argument
Output: [ 'This blog is owned by Muhammad Bilal' ];
15. padStart() & padEnd():
The padStart()
and padEnd()
methods are new String methods introduced in ECMAScript 2017. They allow you to pad a string with another string (multiple times, if needed) until the resulting string reaches a given length.
padStart():
Pads the string at the start.
padEnd():
Pads the string at the end.
Both methods take two argumentstargetLength
and padString.
targetLength
The desired length of the resulting string.
padString
The string to use for padding. If missed out, then the default padding character is " " (space).
For Example:
padStart() Example:
let strStart = "Pad";
console.log(strStart.padStart(5, "*"));
// We set length as 5, variable pad has 3 characters
// it have to ccomplete its 5 character length
// so "+" fills those remaining 2 as **
Output: **Pad
padEnd() Example:
let strEnd = "Pad";
console.log(strEnd.padEnd(10, "+"));
// We set length as 10, variable pad has 3 characters
// it have to ccomplete its 10 character length
// so "+" fills those remaining 7 as +++++++
Output: Pad+++++++
let strStart = "Pad";
console.log(strStart.padStart(8)); // Without padstring
console.log(strStart.padStart(8, " ")); // padstring empty
// It fills itself with white spaces if padstring is missing or empty
Output: Pad
Note:
The padStart()
and padEnd()
methods are supported by all modern browsers, except for Internet Explorer 11 and older. If you need to support older browsers, you can use a polyfill, such as the one from the core-js library.
16. search():
The search()
method is a built-in method of the String object in JavaScript that searches a string for a specified value and returns the index of the first match. It also takes the second argument position
which is an optional parameter. It means the position where to start. If nothing is present in it then it returns -1.
It is also case-sensitive.
For Example:
let searchString = "This is JavaScript in Depth blog series";
console.log(searchString.search("ri"));
Output: 14
// We can search it as a regular expression(regexp) also
let searchReg = "This is JavaScript in Depth blog series";
console.log(searchReg.search(/ri/)); // it search same as string
Output: 14
17. match():
The match()
method is used to search for matches of a regular expression in a string.
match():
Returns an array containing the first match or null if no match is found.
match():
This does not require the global flag (g) to be set.
match():
Returns the entire match and any capturing groups if the capturing groups are present.
For Example:
match() Example:
let matchString = "This is JavaScript in Depth blog series";
console.log(matchString.match('in')); // Search With string
Output: [
'in',
index: 19,
input: 'This is JavaScript in Depth blog series',
groups: undefined
]
let matchString = "This is JavaScript in Depth blog series";
console.log(matchString.match(/ri/)); // Search with regexp
Output:
[
'ri',
index: 14,
input: 'This is JavaScript in Depth blog series',
groups: undefined
]
// match() Example with global regular expression
let matchString = "This is JavaScript in Depth blog series RI";
console.log(matchString.match(/ri/g)); // Search with global regexp
Output: [ 'ri', 'ri' ]
// match() Example with global flag case insensitive regular expression
let matchString = "This is JavaScript in Depth blog series RI";
console.log(matchString.match(/ri/gi)); // Search with global flag
// case insensitive regexp
Output: [ 'ri', 'ri', 'RI' ]
18. matchAll():
matchAll()
methods is used to search for matches of a regular expression in a string.
matchAll():
Returns an iterator that returns all matches of the regular expression in the string.
matchAll():
Requires the global flag (g) to be set.
matchAll():
Returns an iterator that returns an object for each match, including the entire match and any capturing groups.
For Example:
matchAll() Example:
let matchAllString = "This is JavaScript in Depth blog series RI";
let res = matchAllString.matchAll('ri');
let res1 = matchAllString.matchAll(/ri/g);
// Both of res and res1 are same in the matchAll() method
// matchAll() method return an array
// and this returned array can be accessed by (forOf) loop
for(let rest of res1){
console.log(rest);
}
Output:
[
'ri',
index: 14,
input: 'This is JavaScript in Depth blog series RI',
groups: undefined
]
[
'ri',
index: 35,
input: 'This is JavaScript in Depth blog series RI',
groups: undefined
]
// matchAll() regexp for case in sensitive
let matchAllReg = "This is JavaScript in Depth blog series RI";
let res = matchAllReg.matchAll('ri');
let res1 = matchAllReg.matchAll(/ri/gi); // Case insensitive
// matchAll() method return an array
// and this returned array can be accessed by (forOf) loop
for(let rest of res1){
console.log(rest);
}
// Output:
[
'ri',
index: 14,
input: 'This is JavaScript in Depth blog series RI',
groups: undefined
]
[
'ri',
index: 35,
input: 'This is JavaScript in Depth blog series RI',
groups: undefined
]
[
'RI',
index: 40,
input: 'This is JavaScript in Depth blog series RI',
groups: undefined
]
Note:
It is just like the search()
method but the difference is if search()
finds no value then it returns -1
and if match() & matchAll()
finds no value they return Null.
19. replace() & replaceAll():
Both replace and replaceAll methods are used to modify a string in JavaScript. Both take two arguments, The first is that which you want to replace and the second is that you want to replace with. The difference is that:
replace():
This method searches for the first occurrence of the specified pattern (string or regular expression) in the given string and replaces it with the provided replacement string.
It only affects the first occurrence of the pattern, leaving other occurrences untouched.
This method is useful for simple replacements where you only need to change the first instance of a specific string.
For Example:
let replaceStr = "This blog is for in-depth knowledge. This is for you.";
console.log(replaceStr.replace("This", "The"));
// It just effect the first occurance only
// OutPut:
The blog is for in-depth knowledge. This is for you.
replaceAll():
This method, introduced in ECMAScript 2021, searches for all occurrences of the specified pattern (string or regular expression) in the given string and replaces them with the provided replacement string.
It modifies the entire string, replacing all instances of the pattern.
This method is ideal for situations where you need to replace all occurrences of a specific pattern, such as removing all punctuation from a string or converting all characters to lowercase.
For Example:
let replaceAllStr = "This blog is for in-depth knowledge.
This blog is for you.";
console.log(replaceAllStr.replaceAll("This", "The"));
// It effect all the occurance.
OutPut: The blog is for in-depth knowledge. The blog is for you.
Note:
Both replace()
and replaceAll()
return a new string. They do not modify the original string.
When you are using regular expressions with replace()
and replaceAll()
, make sure to include the g flag (global) to ensure all occurrences are replaced.
replaceAll()
is a newer method and may not be supported by all older browsers.
20. concat():
concat()
allows you to join two or more strings together and return a new string.
For Example:
// For two strings
let str1 = "This is in-depth";
let str2 = " JavaScript Blog.";
let str3 = str1.concat(str2);
console.log(str3);
Output: This is in-depth JavaScript Blog.
// For more than two strings
let str1 = "This is in-depth";
let str2 = " JavaScript Blog.";
let str3 = " This is for you.";
let strOutput = str1.concat(str2,str3);
console.log(strOutput);
Output: This is in-depth JavaScript Blog. This is for you.
Note:
concat()
does not modify the original string. It creates a new string with the combined content.You can concatenate any number of strings, including none. If no arguments are provided, an empty string is returned.
You can also concatenate other data types to a string using
concat()
. If the data type can be converted to a string, it will be included in the final result.
Instead/Alternative of concat()
We also use (+)
the operator for the concatenation of strings.
For Example:
let str1 = "This is in-depth";
let str2 = " JavaScript Blog.";
let str3 = " This is for you.";
let strOutput = str1 + str2 + str3;
console.log(strOutput);
Output: This is in-depth JavaScript Blog. This is for you.