Strings in JavaScript

String LiteralsString Methodssubstring() Vs slice()var Vs letimmutable

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

var string1 = "Welcome to JavaScript Blog";
var string2 = 'Strings in JavaScript';
var string3 = 'I\'m planning to go out';
console.log("String 1:", string1);
console.log("String 2:", string2);
console.log("String 3:", string3);

Output

String 1: Welcome to JavaScript Blog
String 2: Strings in JavaScript
String 3: I'm planning to go out

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

SequenceCharacter represented
\0The NUL character (\u0000)
\bBackspace (\u0008)
\tHorizontal tab (\u0009)
\nNewline (\u000A)
\vVertical tab (\u000B)
\fForm feed (\u000C)
\rCarriage return (\u000D)
\”Double quote (\u0022)
\’Apostrophe or single quote (\u0027)
\\Backslash (\u005C)
\x XXThe Latin-1 character specified by the two hexadecimal digits XX
\u XXXXThe 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

const str1 = "Welcome to JavaScript Blog: ";
const str2 = "Strings in JavaScript";
const len1 = str1.length;
const len2 = str2.length;
console.log("The length of the first string is: ",len1);
console.log("The length of the second string is: ",len2);

Output

The length of the first string is:  28
The length of the second string is:  21

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

const str1 = "Hello";
const str2 = "Welcome to JavaScript Blog";
console.log(str1.toUpperCase());
console.log(str2.toLowerCase());

Output

HELLO
welcome to javascript blog

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

const str1 = "Hello";
const str2 = "Welcome to JavaScript Blog";
console.log(str1.indexOf("llo"));
console.log(str2.indexOf("JavaScript"));

Output

2
11

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

const str1 = "Hello";
const str2 = "Welcome to JavaScript Blog";
console.log(str1.substring(4));
console.log(str2.substring(4,10));

Output

o
ome to

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

const str1 = "Hello";
const str2 = "Welcome to JavaScript Blog";
console.log(str1.slice(4));
console.log(str2.slice(4,10));

Output

o
ome to

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():
const strValue= "welcome";
console.log(strValue.substring(-2));

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

console.log(strValue.substring(6, -1));

In the above example, -1 will become 0 and act as a start argument and 6 will act as an end argument, i.e.,

console.log(strValue.substring(0,6)); // Output: welcome


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:

console.log(strValue.slice(-2)); // Output: me
console.log(strValue.slice(0, -1)); // Output: welcom

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

const strTemp = "Welcome to JavaScript Blog";
console.log("Before using replace() method: ",strTemp);
console.log("After using replace() method: ",strTemp.replace("JavaScript", "String Methods"));

Output

Before using replace() method:  Welcome to JavaScript Blog
After using replace() method:  Welcome to String Methods Blog

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

const strTemp = "Good Morning, Hello, Welcome";
console.log(strTemp.split(","));

Output

[ 'Good Morning', ' Hello', ' Welcome' ]

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

const strTemp = "        Welcome to JavaScript Blog            ";
console.log("Before using trim() method:",strTemp);
console.log("After using trim() method:",strTemp.trim());

Output

Before using trim() method:         Welcome to JavaScript Blog
After using trim() method: Welcome to JavaScript Blog

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

const strTemp = "Welcome to JavaScript Blog";
console.log(strTemp.charAt(11));

Output

J

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

const strTemp1 = "Welcome to JavaScript Blog";
const strTemp2 = "Strings in JavaScript";
console.log(strTemp1.startsWith("Welcome"));
console.log(strTemp2.endsWith("Blog"));

Output

true
false

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

const str1 = "Welcome to JavaScript Blog";
console.log(str1.includes("Blog"));

Output

true

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

const str1 = "Welcome to JavaScript Blog: ";
const str2 = "Working with Strings in JavaScript";
const str3 = str1 + "" + str2;
const str4 = str1.concat(" *", str2);
console.log(str3);
console.log(str4);

Output

Welcome to JavaScript Blog: Working with Strings in JavaScript
Welcome to JavaScript Blog: *Working with Strings in JavaScript

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

const str1 = "Good Morning, Hello, Welcome";
const str2 = "Welcome to JavaScript Blog";
console.log(str1.localeCompare(str2));

Output

-1

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.