JavaScript Strings

Javascript-strings-feature.jpg

If you are new to JavaScript, one of the first things that you will learn about is strings. Strings are significant data types, which are used to read and manipulate text. Strings can be used to print messages, get user input, and deal with web APIs. They are a series of characters (letters, numbers, or symbols) that could be treated as a primitive or basic data type.

In this blog, you will learn about what strings are, how they work in JavaScript, the different methods of strings, and how you can use them in an effective way. So let’s get started!

Table of Contents

What is a String in JavaScript?

In JavaScript, a string refers to a set of characters, e.g., letters, numbers, or characters that can be used to represent text. A string can be created by putting the text inside single quotes(‘ ’) or double quotes(“ ”). These strings can be useful when you want to work with a person’s name, a paragraph, or even a piece of code.

While working with strings, JavaScript provides you with many built-in tools that are called string methods. These methods help you to perform tasks like changing the case of letters, finding specific words, replacing parts of the text, or even splitting the string into pieces. These methods make it easier for you to handle inside your code.

A sample code is given below, which shows how strings work in JavaScript:

Code:

Javascript

Output:

String in JavaScript

Explanation:

The above JavaScript code is used to create a welcome message. It uses the name “Intellipaat” and uses it with the word “Hello”. After that, it prints the message and converts the name to uppercase, joins the greeting and name, and checks if the message contains the word “Welcome” using methods in JavaScript.

Master Web Development
Learn to Build Stunning Websites and Apps from Scratch
quiz-icon

How to Create Strings in JavaScript?

In JavaScript, you can create a string in multiple ways. Each method is very easy to implement and has its own purpose. Given below are some common ways to create strings in JavaScript:

1. Create using Literals 

The simplest and easiest method of creating strings in JavaScript is by using either single or double quotation marks, i.e., single quotes (‘ ’) or double quotes (“ ”). You can choose either of the two ways to create a string.

Code:

Javascript

Output:

Create using Literals

Explanation:

The above code shows how you can create strings in JavaScript using single and double quotes. After that, it prints them to the console.

2. Create using a Constructor

You can use the new String() constructor to create a special string object, not a regular string. It is not usually recommended because it can lead to confusing results when they are compared with normal strings.

Code:

Javascript

Output:

Create using a Constructor

Explanation:

The above code is used to create a string object using the new String() and then prints it. It shows it as an object instead of a string.

3. Template Literals (String Interpolation)

You can also create strings using template literals. This means that you should write your text inside backticks ( ` ). This helps you to add variables or expressions into the string easily. Hence, it makes it easier for you to read and work with it.

Code:

Javascript

Output:

String Interpolation

Explanation:

The above JS code uses a template literal in order to insert the value of s1 into a string. After that, it prints the output.

4. Empty String

For creating an empty string by using single or double quotes only, without writing any content inside them.

Code:

Javascript

Explanation:

The above JS code is used to create two empty strings using single and double quotes. After that, it prints them, but shows blank lines in the output.

5. Multiline Strings

In order to create a multiline string, you can use backticks (). This helps to keep the line breaks exactly in the way you write them.

Code:

Javascript

Output:

Multiline string

Explanation:

The above JS code is used to create a string that has multiple lines. It uses backticks and then prints it using the same line breaks that you have written.

Get 100% Hike!

Master Most in Demand Skills Now!

JavaScript String Methods

In JavaScript, when a method is used on a regular string. JavaScript automatically treats it like a string object to make sure that the method works. This is called auto-boxing. Given below are some important JavaScript String methods:

1. slice() method

The slice() method in JavaScript helps you to cut out a part of a string. It provides you with a starting index and an ending index. It then gives you a new string.

Code:

Javascript

Output:

slice() method

Explanation:

The above code uses the slice() method to extract different parts of the string “Intellipaat”. After that, it prints each part separately.

2. substring() method

In JavaScript, the substring() method gives you a part of a string. It starts from one position and ends just before the other. The counting starts from zero.

Code:

Javascript

Output:

substring() method

Explanation:

The above JS code takes the characters from the 6th to 10th positions in the string. After that, it uses substring() and prints, “Power”.

3. substr() method

The substr() method helps you to take a piece of a string. It tells the string from where it should start and how many characters it should include. It then provides you with that part of the original string.

Code:

Javascript

Output:

substr() method

Explanation:

The above JS code is used to take 5 characters from the string. It starts from the 6th position using substr() and then prints “Power”.

4. replace() method

The replace() method in JavaScript allows you to swap a part of a string with something else, like another word or pattern. It does not change the original string; it just provides you with a new one.

Code:

Javascript

Output:

replace() method

Explanation:

The above JS code replaces the word “Power” with “Space” in the string. After that, the updated screen is printed.

5. replaceAll() method

The replaceAll() method in JavaScript is used to create a new string. It replaces every substring with something else. It does not change the original string.

Code:

Javascript

Output:

replaceAll() method

Explanation:

The above code replaces the word “Power” with “Space” in the string. After that, it prints the new result.

6. toUpperCase() method

The toUpperCase() method is used to change all the letters in a string to capital letters and provides you with a new string. You just have to use it on the string you want to convert to uppercase.

Code:

Javascript

Output:

toUpperCase() method

Explanation:

The above code converts the string “Intellipaat” to “INTELLIPAAT” using the toUpperCase() method. It then prints “INTELLIPAAT”.

7. toLowerCase() method

The toLowerCase() method of JavaScript is used to change all the letters in a string to lowercase letters. It then prints a new string.

Code:

Javascript

Output:

toLowerCase() method

Explanation:

The above JS code changes all the letters in “Intellipaat” to small letters using the toLowerCase() method. It then prints “intellipaat”.

8. concat() method

The concat() method in JavaScript is used to join two strings. It then gives you a new string that is combined. You can use this method by calling the method in one string and passing the other string as an argument inside the quotes.

Code:

Javascript

Output:

concat() method

Explanation:

The above code joins two strings, “IP” and “stands for Intellipaat”. It uses the concat() method and prints the result: “IP stands for Intellipaat”.

9. trim() method

The trim() method in JavaScript is used to remove extra spaces from the beginning and end of a string and gives you a cleaned-up string in return. It does not take any input.

Code:

Javascript

Output:

trim() method

Explanation:

The above JS code removes all the extra spaces from the end of the string “Intellipaat”. It uses the trim() method and then prints the length before and after removing the spaces.

10. trimStart() method

The trimStart() method in JavaScript is used to remove spaces only from the beginning of a string; it does not remove the spaces that come after the text. It does not change the original string.

Code:

Javascript

Output:

trimStart() method

Explanation:

The above code is used to remove the spaces at the beginning of the string “ Soul” using the trimStart() method. It then prints the updated version: “Soul”.

11. trimEnd() method

The trimEnd() method in JavaScript is used to remove spaces only at the end of a string. It keeps the spaces that were before the beginning of the text. It does not change the original string.

Code:

Javascript

Output:

trimEnd() method

Explanation:

The above JS code is used to remove the extra spaces at the end of the string “Soul ”. It uses the trimEnd() method and then prints the updated result: “Soul”.

12. padStart() method

The padStart() method in JavaScript is used to add extra characters at the beginning of the string until the string reaches a length that you have set. It also helps you to format text in order to match a certain size.

Example:

Javascript

Output:

padStart() method

Explanation:

The above code is used to add the string “Mind ” at the beginning of “Soul” until the total length of the string becomes 9 characters. After that, it prints the results.

13. padEnd() method

The padEnd() method in JavaScript is used to add extra characters at the end of a string until it matches the length you want.

Code:

Javascript

Output:

padEnd() method

Explanation:

The above JS code is used to add the string “Power” to the end of “Soul” until the length of the string becomes 10 characters. After that, it prints the result.

14. charAt() method

The charAt() method in JavaScript gives you the character from a string at the position that you want, starting from index 0.

Code:

Javascript

Output:

charAt() method

Explanation:

The above code is used to print two strings and then shows the characters at specific positions( first from ip and sixth from info). It uses zero-based indexing for this.

15. charCodeAt() method

The charCodeAt() method in JavaScript provides you with the “UTF-16 code unit” of the character at a particular position in a string. It takes only one number as input. 

Code:

Javascript

Output:

charCodeAt() method

Explanation:

The above code is used to print the Unicode values of characters at specific positions in the strings “ip” and “info”.

16. Split() method

The split() method is used to break a string into smaller parts depending on the character that you choose. It returns those parts as an array.

Code:

Javascript

Output:

split() method

Explanation:

The above JS code is used to split the info string into an array of words in the places where there is a hyphen ( ). After that, it prints the array.

Common Use Cases of Strings in JavaScript

1. Saving what a user types or selects.

2. Showing messages or alerts on a webpage.

3. Navigating with website links, date manipulation, and interaction with online services (APIs)

4. Creating content using templates that change based on the user.

Conclusion

Strings in JavaScript are an important part of any application that you develop using JavaScript. Starting from simple alerts to complex templates, they are used everywhere. Learning JavaScript String Methods will help you to control and change the way your applications respond to text. You should keep practicing these methods in order to master string manipulation. If you are an aspiring web developer, explore our blog and enroll in our Web Development Course.

JavaScript Strings – FAQs

Q1. What is the difference between slice() and substring() in JavaScript?

The slice() method accepts negative indexes, but the substring() method does not.

Q2. Can I change characters in a string directly?

No, JavaScript strings are not mutable. The new string has to be created.

Q3. How do I check if a string contains a word?

Use the includes() method like “JavaScript”.includes(“Script”).

Q4. What is the output of "5" + 3 in JavaScript?

It returns the string “53” due to type coercion.

Q5. How do I count the number of words in a string?

Use split (” “) and then check the .length of the array.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner