Strings in JavaScript
In the Numbers in JavaScript blog, we learned about what numbers are. In JavaScript, numbers represent numerical values. They can be integers or floating-point decimals. You can perform arithmetic operations, such as addition and multiplication, using numeric values in JavaScript. In this blog, we will learn about the Strings in JavaScript.
What are Strings?
In JavaScript, to store the textual data, we use a string. A string is an immutable,ordered sequence of 16-bit values, each of which typically represents a Unicode character. Strings use zero-based indexing, i.e., the first character of the string is stored on the 0th index location, the second character on the 1st index location, and so on. Strings are written in either single quotes, double quotes, or backticks.
What is an immutable String?
Immutable in general is nothing but the property of the data that cannot be changed or modified. The same is applicable for string i.e., once the string is created, its value cannot be changed or modified. In order to change a string, new string should be created with the changes.
For example, if a string is stored in the variable, string cannot be modified directly; rather, new string is created and put back in the same variable.
Let's take a look at the example:
let empName = "ABC";
empName = "XYZ" ;
In the above example, the name "ABC" will still exist in the memory, but the variable name will refer to "XYZ"
String Literals
We can create a String using single quotes(‘ ’), double quotes(“ ”) or backticks(`). We can use double-quote characters inside strings enclosed by single quotes, and vice versa. For example:
“Don’t open the door”
“It's too late”
“Let’s go home” etc.
When you use single quotes to surround your text, be cautious with English contractions and possessives like "can't", "Teachers’ Day",“It’s”, etc. Since the apostrophe is similar to the single-quote character, you must use the backslash character (\) to "escape" any apostrophes within single-quoted strings. Let’s take a look at the example
Output
Escape Sequence in String Literals
In JavaScript, the backslash character (\) serves a special role in strings. When paired with the character immediately after it, it creates a representation for a character that might be challenging to include directly in the string. For example, “\n” is used to represent a new character. Another example is “\” escape sequence, which is used to represent the single quote character or apostrophe. This escape sequence is useful when we want to include an apostrophe in a string literal that is contained within single quotes. Below the table of all the escape sequences
Sequence | Character represented |
---|---|
\0 | The NUL character (\u0000) |
\b | Backspace (\u0008) |
\t | Horizontal tab (\u0009) |
\n | Newline (\u000A) |
\v | Vertical tab (\u000B) |
\f | Form feed (\u000C) |
\r | Carriage return (\u000D) |
\” | Double quote (\u0022) |
\’ | Apostrophe or single quote (\u0027) |
\\ | Backslash (\u005C) |
\x XX | The Latin-1 character specified by the two hexadecimal digits XX |
\u XXXX | The Unicode character specified by the four hexadecimal digits XXXX |
String Methods
JavaScript provides a variety of methods for working with strings. Here are some common methods and operations you can perform on JavaScript strings:
length
In JavaScript, the length property is used to determine the number of characters in a string. Let’s take an example
Output
In the above example, we have two strings, i.e., str1 and str2. If we count the character in string 1, i.e. in str1, the length is 28and for str2, the length is 21
toUpperCase() and toLowerCase()
We use the toUpperCase() method to convert all the characters in the string to uppercase. Similarly, in order to convert all the characters in the string to lowercase, we use the toLowerCase()method. Let take a look at the example
Output
In the above example, str1 is displayed in uppercase and str2 is displayed in lowercase
indexOf()
In JavaScript, the indexOf() method is used to find the index of the first occurrence of a specified value within a string. It returns-1, if the value is not found. Let’s take a look at the example
Output
In the above example, for the substring “llo” in str1 the index of lis 2 and similarly for substring “JavaScript” in str2 the index of Jis 11
substring()
substring() method is used to extract the part of the string based on the starting and ending indexes. Let’s take a look at the example
Output
In the above example, we have two strings str1 and str2. For str1, we have extracted the part of the string from the 4th index, i.e.,o. For str2, we have extracted the part of the string from 4th index location to 10th index location, i.e. ome to.
slice()
slice() method is used to extract a part of a string based on starting and ending indexes. Let’s take a look at the example
Output
In the above example, we have two strings str1 and str2. For str1, we have extracted the part of the string from the 4th index, i.e.,o. For str2, we have extracted the part of the string from 4th index location to 10th index location, i.e. ome to.
What is the difference between the substring() and slice() method in javascript?
The difference between substring() and slice() is that in the `substring()` method, if the index is negative, it is treated as if it is 0 (zero). On the other hand, in the `slice()` method, if the index is negative, then it counts from the end of a string.
Let’s take a look at the example,
substring():In the above example, -2 is interpreted as 0. So here, -2 will become 0, and it will display the test starting with index 0. Similarly, if start is greater than end, then the arguments interchanged. Let take a look at the example
In the above example, -1 will become 0 and act as a start argument and 6 will act as an end argument, i.e.,
slice():
On the contrary, in the slice() method, negative values are measured from the end of the line. Let’s take a look at the example:
replace()
replace() method is used to replace a substring with another string. It allows us to search for a specified substring or a regular expression pattern within a string and replace it with another substring or a function that defines the replacement. Let’s take a look at the example
Output
In the above example, the substring i.e. JavaScript, in strTemp is replaced with String Methods
split()
split() method is used to split or divide a string into an array of substring on the basis of a delimiter. Let’s take a look at the example
Output
In the above example, a comma(,) is used as a delimiter to divide the string.
trim()
trim() method is used to remove the leading and trailing spaces from the string. Let’s take a look at the example
Output
In the above example, strTemp has leading and trailing spaces. By using trim() method the leading and trailing spaces are removed.
charAt()
charAt() method is used to return the character at the specified index in the string. Let’s take a look at the example
Output
In the above example, the character at the 11th location in the string i.e. J is displayed.
startsWith() and endsWith()
startsWith() method is used to check if the string starts with a specified substring. This method returns a Boolean value (`true` or`false`) indicating whether the string begins with the specified substring. Similarly endsWith() method used to check if the string ends with a specified substring. This method returns a Boolean value (`true` or `false`) indicating whether the string ends with the specified substring. Let’s take a look at the example
Output
In the above example, in strTemp1 we have checked if the string starts with Welcome. As the string starts with welcome, so the result is true. Similarly, in strTemp2, we have checked if the string ends with Blog. As the string not ends with Blog, the result is false
includes()
includes() method checks if the string contains a specific substring. This method returns a Boolean value (`true` or `false`) indicating whether the string contains the specified substring. Let’s take a look at the example
Output
In the above example, we have checked if the string includes Blog. Because the string contains the word Blog, the result is true.
concat()
concat() or + method concatenates two or more strings and returns a new string. Let’s take a look at the example
Output
In the above example, we have combined two string and concatenated a special symbol, an asterisk(*) before the word Working
localeCompare()
localeCompare() method compares two strings based on their lexicographical order, taking into account the current locale. Let’s take a look at the example
Output
What is the difference between the var and let in javascript?
In JavaScript, var has function-level scope, making a variable accessible throughout the entire function, even if declared inside a block like an if statement or a loop. On the flip side, let has block-level scope, meaning it's only accessible within the specific block, statement, or expression where it's defined and won't extend beyond those boundaries.
In JavaScript, strings are sequences of characters. String methods like toUpperCase() and indexOf() help manipulate and search within strings. Understanding and using these methods enhances string handling in our code, making it more efficient and versatile.