Introduction to JavaScript Strings & Methods

ยท

15 min read

Introduction to JavaScript Strings & Methods

Strings are an essential part of any programming language & JavaScript is no exception. In this article, we will dive into the world of strings, studying everything from the basics of string declaration to the more advanced string methods. There are some prerequisites to this article: You might want to check out my articles on:

These articles will help you familiarize JavaScript basics.

If you're new to JavaScript and looking to deepen your understanding of strings, this guide has something for you. I will cover topics, including string declaration, common string methods, and practical examples that illustrate the power and versatility of strings in JavaScript. So buckle up, and let's start our journey to mastering strings in JavaScript!

Definition:

Strings are used to represent text and are enclosed in single '', double " ", or backticks ` ` and can contain letters, numbers, and special characters.

String values cannot be changed once they are created. However, you can create a new string by concatenating two or more strings together. we will see the concatenation method later on.

Some examples of strings in JavaScript include:

let string1 = "Hello, world!";    // Text
console.log(string1);      

let string2 = '1 2 3 4 5 6 7 8 9 0';   // Number
console.log(string2);

let string3 = `! @ # $ % ^ & * ( )`;   // Special characters
console.log(string3);

In this example, we define 3 string variables: string1, string2, and string3. string1 is assigned the value "Hello, world!" in double quotes, which is a text string.

string2 is assigned the value '1 2 3 4 5 6 7 8 9 0' in single quotes, which is a string of numbers separated by spaces. string3 is assigned the value `! @ # $ % ^ & * ( )` in backticks, which is a string of special characters. Then we log each of the three strings to the console using the console.log() method.

The output would be in Browser's console:

Quotes inside strings:

  • We cannot use the same quotes inside the string if we are using them surrounding the string.

    For example:

      let string = 'It's a string.';
      console.log(string);
    

    It will give an error if we try to log the string to the console.

    Here is what you can expect from this:

  • But we can use quotes inside a string if we use different quotes to surround the string.

    For example:

      let string1 = "It's a string.";
      console.log(string1);
    
      let string2 = 'He replied,"Yes!".';
      console.log(string2);
    

    It will work just fine. Here is what you can expect from this:

We can also do this with a different approach known as escaping the character. let's see how we can do this.

Escaping the character:

This method comes in handy when we want to put some special characters like double quotes ", single quotes ', or backslash \ inside the string. All we need to do is put the backslash (\) escape character before these special characters. The backslash means that whatever comes after it has special meaning. Quotes after the backslash (\) escape character will not end the string instead it will be part of it.

For example:

let string1 = 'It\'s a string.';
console.log(string1);

let string2 = "He replied,\"Yes!\".";
console.log(string2);

let string3 = ' backslash (\\) escape character';
console.log(string3);

See the output in the browser's console:

Types of Strings:

Strings in JavaScript can be created in three ways:

Primitive Strings:

This type of string is simple that can be used to define text date, which we cannot change because string primitives are immutable and have a limited set of methods. Primitive strings are created using string literals. It's a sequence of characters enclosed in either single quotes ' ' or double quotes " ".

You can know more about Primitive datatypes in one of my articles, where I have explained everything about it in detail.

For example:

let stringPrimitive1 = 'Ansari'; // Single quotes
let stringPrimitive2 = "Yasir"; // Double quotes

Due to their simplicity, we can easily manage string primitives in JavaScript. For example, Using the + operator, we can join or concatenate strings together:

let concatenation = "Hi, " + stringPrimitive1 + ' ' +stringPrimitive2 + '.';
console.log(concatenation);

Above what we did is declared two string primitive variables stringPrimitive1 and stringPrimitive2 with values "Ansari" and "Yasir" respectively. The third variable concatenation is assigned the result of concatenating these two strings along with three other string literals: "Hi, ", " ", and ".". The concatenated string is logged to the console using console.log and the output would be: Hi, Ansari Yasir..

See the output in the browser's console:

Template literals:

Template literals are often called "Template strings". It gives more control over dynamic strings. It's use back-ticks ` ` rather than quotes " " or ' ' to define a string.

  • Quotes Inside Strings:

    With help of template literals, we can use quotes inside the string.

      let temp1 = `It's "Yasir Ansari"`;
      console.log(temp1);
    

    The output would be in Browser's console:

  • Multiline Strings:
    We don't need to write \n in the string for new in a template literal. It allows multiline strings.

      // Multiple strings
      let temp2 =
      `It will give 
      output exactly as
      we are going to 
      write in it.`;
    
      console.log(temp2);
      // Output will be as it is with mutliple lines:-
    

    The output would be in Browser's console:

  • Interpolation of variables and expressions:

    Template literals also variables and expressions into strings. It's very helpful to add dynamic values using the string interpolation method in a template literal. Syntax: ${expression} .

    1. Variables:

       let firstName = 'Yasir';
       let lastName = 'Ansari';
       console.log (`My fullname is ${firstName } ${lastName}`);
      

      The output would be in Browser's console:

    2. Expressions:

       let val1 = 1, val2 = 2;
       let addition = `Addition of ${val1} + ${val2} = ${val1 + val2}`;
       console.log(addition);
      

      The output would be in Browser's console:

Remember Template literals are modern features of JavaScript and we are going to use them quite often in JavaScript programming.

String Objects:

Until now, we have defined the Javascript string as primitive values with double or single quotes or backticks. But in Javascript, we can also define strings as objects using the String() constructor with the new keyword. String objects are mutable and have a more extensive set of methods and properties (To know more about Objects).

For example:

// Primitive String:
let stringPrimitive = "JavaScript";
console.log(stringPrimitive);

// String Object:
let stringObject = new String("JavaScript");
console.log(stringObject);

See how string objects return the result when we log them to the console:

If we check their date types using the typeof operator, we will get a result quite different.

For example:

let stringPrimitive = "JavaScript";
console.log(typeof stringPrimitive);

let stringObject = new String("JavaScript");
console.log(typeof stringObject);

Here what we are trying to do is declared two strings, stringPrimitive and stringObject, with the value "JavaScript". The typeof operator is used to get the data type of each string.

The output would be in Browser's console:

Using typeof on stringPrimitive, it returns "string", indicating that stringPrimitive is a string primitive. But when using typeof on stringObject, it returns "object", indicating that stringObject is a string object, created using the String constructor.

Comparing both primitive & object strings:

Take an example, where we are going to assign the same value to both types of strings, then we will check the results by comparing them with == & === operator [Know more about the Difference Between == & === operator in one of my previous articles].

let string1 = 'same';
let string2 = new String('same');

console.log(string1 == string2); 

console.log(string1 === string2);

So what is happening here, we defined two strings, string1 & string2, with the same value "same". And we try to compare them using == & === operators.

Now look what will happen if we log the above example to the console:

  1. The == operator compared string1 and string2 for equality and returned true. This is because it performed type coercion, automatically converted the string object string2 to a string primitive before comparing.

  2. The === operator compared string1 and string2 for equality without type coercion and returned false. This is because string1 is a string primitive, while string2 is a string object, and the === operator only returns true if both operands have the same type and value.

I recommend you use primitive string instead of using strings objects. Let me demonstrate why?

While using string objects, you might get unexpected results and complications in the code. It will slow down the execution because string objects are created on the heap and require additional memory allocation.

By using primitive strings, you can ensure that your code runs faster, is less prone to errors, and is easier to maintain. So if you want to write clean, efficient, and maintainable JavaScript code, make sure to use primitive strings whenever possible.

String Methods:

JavaScript provides several built-in methods to work with strings that allow us to exploit and alter strings in various ways. These methods are available on both primitive strings and string objects.

Some of the common string methods include:

1. The string length property:

This is built-in length property used to find the length of the string.

For example:

// Example 1
let string1 = "Hello, world!";    
console.log(string1.length);      

// Example 1
let string2 = '1234567890';   
console.log(string2.length);

In Example 1, we declare a variable string1 and assign it the string value "Hello, world!". Then, the .length property of the string1 object is logged to the console using console.log(string1.length). The .length property returns the number of characters in a string (including spaces).

The output would be in Browser's console:

In Example 2, we declare a variable string2 and assign it the string value '1234567890'. Then, the .length property of the string2 object is logged to the console using console.log(string2.length). The .length property returns the number of characters in a string.

The output would be in Browser's console:

2. The toUpperCase() method:

It converts a string to uppercase. For example:

let name = 'Ansari Yasir';
console.log(name.toUpperCase());

The output would be in Browser's console:

In the above example: We used toUpperCase() method on a string value 'Ansari Yasir', which returned a new string with all uppercase characters. The result of name.toUpperCase() is logged to the console and is equal to: 'ANSARI YASIR'.

3. The toLowerCase() method:

It converts a string to lowercase. For example:

let name = 'Ansari Yasir';
console.log(name.toLowerCase());

The output would be in Browser's console:

In the above example: We used the toLowerCase() method on a string value 'Ansari Yasir', which returned a new string with all lowercase characters. The result of name.toLowerCase() is logged to the console and is equal to 'ansari yasir'.

4. The slice(start, end) method:

It slices out a part of the string and returns the extracted part in a new string, starting from the index specified by start and ending at the index specified by end. (end index is not included in the slicing part). If you omit the second parameter, the method will slice out the rest of the string. We can also use the -ve parameter, the position is counted from the end of the string.

For example:

let name = 'Ansari Yasir.';
console.log(name.slice(0, 2));
console.log(name.slice(-4, -1));

The output would be in Browser's console:

In the above example: We used the slice() method on a string value 'Ansari Yasir.'. In the first console.log() statement, the slice() method is called arguments 0 and 2. This returned a new string starting from the 0th index (A) up to, but not including, the 2nd index (s). The result of name.slice(0, 2) is 'An'.

In the second console.log() statement, the slice() method is called arguments -4 and -1. So, the -4 index refers to the 4th character counting from the end of the string (s) and the -1 index refers to the last character (r) of the string. The slice() method returned a new string starting from the -4 index up to, but not including, the -1 index. The result of name.slice(-4, -1) is 'sir'.

5. The substr(start, length) method:

it is similar to slice() with a slight difference, here the second parameter specifies the length of the extracted part.

For example:

let name = 'Ansari Yasir.';
console.log(name.substr(0, 2));
console.log(name.substr(-4, 3));

The output would be in Browser's console:

In the above example: We used the substr() method on a string value 'Ansari Yasir.'. In this first, we called substr() with arguments 0 and 2. The 0 index refers to the first character of the string and the length of 2 characters will be returned starting from the first character. The result name.substr(0, 2) is An.

The second call to substr() with arguments -4 and 3. The -4 index refers to the 4th character counting from the end of the string (s). The length of 3 character will be returned starting from this index. The result name.substr(-4, 1) is sir.

6. The split("separator", limit) method:

This method will split a string into an array of substrings based on the specified separator. The first argument of the split() method is the separator that is used to split the string. The second argument is an optional limit, which sets the maximum number of items in the final array.

For example:

let name = 'Hi I am a coder';
console.log(name.split(" ", 3));

The output would be in Browser's console:

In this example, We split the string "Hi I am a coder" into an array of substrings with a separator of " " (space), and the limit was set to 3, so the resulting array contains only the first three elements ["Hi", "I", "am"]. If you do not the set limit, then it will split the whole string.

7. The trim() method:

It will eliminate the spaces from both the start & end of the string. For example:

let name = '   Ansari Yasir      ';
console.log(`${name} = ${name.length}`);
let nameTrim = name.trim();
console.log(`${nameTrim} = ${nameTrim.length}`);

In this example, We defined name string = ' Ansari Yasir ' with extra spaces at the beginning and end of the string. console.log outputs the original string name and its length. Then we called, name.trim() to remove the extra spaces & stored the new string nameTrim. Finally, console.log outputs the new string nameTrim and its length, which is smaller than the length of the original string because of the removed spaces.
See the output in the browser's console:

We can also remove space either from the start or end of the string.

For example:

// remove spaces from start of string:
let startTrimed = name.trimStart();
console.log(`${startTrimed} = ${startTrimed.length}`); 

// remove spaces from end of string:
let endTrimed = name.trimEnd();
console.log(`${endTrimed} = ${endTrimed.length}`);

In the above code, there are two variables startTrimed & endTrimed which stores the values name after trimming white spaces from the start and end respectively. The length of the resultant strings is then logged.

See the output in the browser's console:

8. The replace(oldValue, newValue) method:

This method replaces the old value with the newer one. For example:

let name = 'Yasir Ansari';
let newName = name.replace('Ansari', 'Arfat');
console.log(newName);

The output would be in Browser's console:

In the above code, we created a string variable name and assigned it to "Yasir Ansari". Then we created a new variable newName & its value is set to the result of calling the replace() method on name. Then we called, replace() method to replace the first argument, "Ansari", with the second argument, "Arfat", & stored it in the new string newName. The console.log() statement logs this result to the console.

String Search method:

The built-in search methods in JavaScript allow you to easily search within strings and find the desired information. These methods provide various options for searching and can be used to perform various string operations. we will discuss the following search methods:

1. The indexOf() & the lastIndexOf() methods:

The indexOf() method will return the first index of the specified value that can be found in the string, and if the value is not present in the string it will return -1.

The lastIndexOf() method similar to indexOf(), will return the last index of the specified value.

For example:

let name = 'Yasir Ansari';

// First index:
console.log(name.indexOf('a'));

// Last index:
console.log(name.lastIndexOf('a'));

The output would be in Browser's console:

2. The search() method:

It will search a string for a specified value and returns the position of the match. The search() method also accepts regular expressions as a parameter, whereas the indexOf() method only accepts strings. (know more about The search() method)

For example:

let name = 'Yasir Ansari';
let searchExpression = /[A]/;
console.log(name.search(searchExpression));

In the example, the regular expression pattern /[A]/ is used to find the first occurrence of the letter "A" in the string name. The result is the index of the first match which is 6. (Find about the regular expression here)

See the output in the browser's console:

3. The match() method:

This searches a string for a specified value (or pattern) in a string and returns the first match as an array, or null if there's no match.

For example:

let name = 'Ansari Yasir Arfat';
console.log(name.match('a')); 

// g for global search of "a":
console.log(name.match(/a/g));

// i for case-insensitive search of "a":
console.log(name.match(/a/gi));

Let's see what we did in the above examples:

  1. The first example returns an array with the first match of "a" in the string "Ansari Yasir Arfat".

  2. The second example uses the g flag for a global search and returns an array with all occurrences of "a" in the string.

  3. The third example uses both the g and i flags for a global and case-insensitive search and returns the same result as the second example.

See the output in the browser's console:

4. The includes() method:

It will return a boolean value true if the specified value can be found within the string. Otherwise, it returns false.

For example:

let name = 'Ansari Yasir Arfat';
console.log(name.includes('Yaseer'));

The output would be in Browser's console:

In the example, console.log(name.includes('Yaseer')); logs false because the string 'Yaseer' is not included in the string name.

5. The startsWith() & the endsWith() methods:

startsWith() & endsWith() methods return a boolean value indicating whether the string begins or ends with the specified value respectively.

For example:

let name = 'Ansari Yasir Arfat';
console.log(name.startsWith('Ansari')); 

console.log(name.endsWith('Yasir'));

In the above example, we defined a string variable named name and containing the value 'Ansari Yasir Arfat'. Then we used the startsWith() method to check if the string starts with 'Ansari' and the endsWith() method to check if the string ends with 'Yasir'.

The output would be in Browser's console:

Conclusion:

JavaScript provides a rich set of built-in methods for working with strings. These methods cover a wide range of operations, from searching and slicing strings to concatenating and transforming them. Understanding these methods and how to use them effectively is an important part of becoming a proficient JavaScript programmer. Whether you're looking to extract information from a string, manipulate its contents, or simply join strings together, JavaScript's built-in string methods have you covered. With their ease of use and versatility, these methods are valuable tools for anyone working with strings in JavaScript.

Thank you for reading. Feel free to comment on this, if found it useful.

Happy learning.๐Ÿ˜‡๐Ÿ˜‡๐Ÿ˜‡

ย