JavaScript Strings – Find Out Different Methods of String Objects!

Free Web development courses with real-time projects Start Now!!

Any text like “JavaScript”, “Hello DataFlair!” or “How was your day?” represents a string. We’ve been using strings for a long time in our programs now, without even knowing it. Today in this JavaScript tutorial we are going to cover an important concept i.e. JavaScript Strings that will help you with every other programming language you wish to study.

After going through our previous blog on JavaScript Event Types, we hope you have cleared all your concepts related to events. If you haven’t done so, I highly recommend you go through them before continuing with this topic.

Methods of JavaScript Strings

 

After knowing what Event types are, let’s start with our best tutorial on JavaScript Strings.

What are JavaScript Strings?

A string is a set of characters, including letters, numbers, spaces, etc. In JavaScript, a String is a global object, a constructor for strings or a sequence of characters. It stores all the textual data in JavaScript; there is no separate datatype for a single character.

Syntax of JavaScript String

The syntax of defining a String literal is as follows:

var stringName = "string ";
var stringName = "string";

The syntax to create a String global object looks like this, where data is any object that is convertible to a string:

var stringName = new String(data);

With the introduction of ECMAScript 2015, string literals can be “Template literals”, enclosed by the back-ticks (` `). These allow us to embed an expression into a string by wrapping it in ${…} (jQuery syntax). These are also helpful when you want the string to span multiple lines. Its syntax appears as follows:

`string [${some expression}]`

Do you know how to create different objects? If not, then you must definitely go through our tutorial on JavaScript Objects

Multi-line strings

We can insert a multi-line string with the help of the newline character (\n) in a normal string or by using template literals. Try the codes given below in your console.

console.log("string line1 \nstring line2") //string
console.log(`string line1
string line2`) //template literal

You will get the same result for both the statements that looks as follows:

string line1
string line2

Escape notations

Escape notations or escape characters in JavaScript help inserting special characters in the webpage without breaking the code. We use the backslash (\) character to specify a special character. The following table lists the various escape notations you can use in your JavaScript program:

NotationMeaning
\’It adds a single quote in the page.
\”It adds a double quote in the page.
\\It adds a backslash in the page.
\n (Newline)
It takes control to the next line on the page.
\r (Carriage Return)
It returns the program control to the beginning without advancing to the next line.
\v (Vertical Tab)
It inserts a vertical tab (usually 6 newlines) in the page.
\t (Tab)
It inserts a tab (usually 8 spaces) in the page.
\b (Backspace)
It moves the program control backwards, to the previous character.
\f (Form Feed)
It takes control to the start of the next page i.e. advances one full page automatically.

Long literal strings

There is another special use of the backslash character in JavaScript. If you have a long string literal, instead of storing it all in a long -drawn single line, you can test the following two approaches in your console:

"string line1 " +
"string line2 "+
"string line3 " //appends multiple strings with the concatenation operator
"string line1 \
string line2 \
string line3 " //backslash indicating that the string continues on the next line

Make sure there is no space after the backslash character in your program. Both of these produce the same output, shown below:

string line1 string line2 string line3

Try these codes in your console window, explore and experiment with these and see what happens when you alter the code and how the output changes. You can never practice enough, so keep repeating to master these characters.

Strings are immutable

In JavaScript, strings are immutable i.e. they cannot be changed. It is impossible to change the current string or alter a character. The script creates a new string object when you redefine a string value, but it doesn’t affect the existing string object.

The length property

The length property of a JavaScript String returns the length of the string. You can access this property in the same way as you do with all the properties of any object: with a dot operator. Add the following statements in your console to determine the length of the strings, declared with both literal and constructor methods.

Following are the statements you need to execute in the console:

var str = "DataFlair's JavaScript Tutorial"
var string = new String("DataFlair's JavaScript Tutorial")
str // "DataFlair's JavaScript Tutorial"
str.length //31
string // String {"DataFlair's JavaScript Tutorial"}
string.length // 31

JavaScript Strings - string length

JavaScript Strings Methods

Now, we are going to look at some of the most common methods JavaScript provides. These will help you in accessing and manipulating the string. But while using them, do remember that strings are immutable in JavaScript.

1. Accessing characters

We will be using the same String object in all the methods we learn about. Thus, it is better if you store the string value in a file rather than repeating it in the console. Use the following string for this section:

var string = new String("DataFlair's JavaScript Tutorial");

a. charAt()

This String method returns the character at the specified position.

string.charAt(1) // “a"

You can also access a character at a particular position using the bracket notation.

string[1] // “a”

b. charCodeAt()

It returns a number indicating the Unicode value of the character at the specified position.

string.charCodeAt(1) //97

The methods above return an empty string if you search for a character at an index that exceeds the length of the string.

c. indexOf()

It returns the index of the first occurrence of the specified character in the given string.

string.indexOf(“a”) // 1

d. lastIndexOf()

It returns the index of the last occurrence of the specified character in the given string.

string.lastIndexOf(“a”) //29

The last two methods return -1 if the character you are searching the index for is not present in the string.

access character

2. Comparing strings

Strings are always compared character-by-character in alphabetical order. While comparing, if the first letter is the same for both the strings, only then does it move to the next characters in the strings. But there are some problems with the Unicodes of the characters. A lowercase character always stays greater than an uppercase character. This means that the statement “hello DataFlair” > “JavaScript” returns true, even though ‘J’ comes after ‘h’ in the English dictionary. The reason is that the code for ‘J’ and ‘h’ are 74 and 104 respectively. You can achieve this task with the help of JavaScript methods too.

a. localeCompare()

This JavaScript method, inherited by all the String instances returns three values based on the comparison of strings. The value returned by this method is decided as per the following conditions:

string1 > string2 i.e string1 occurs before string21
string1 < string2 i.e string1 occurs after string2-1
string1 == string2 i.e. they are equivalent0

The following are the statements you need to use to compare two strings directly in the console:

var string1 = “hello DataFlair”
var string2 = “JavaScript”
string1 > string2 // true
string1 < string2 // false
string1.localeCompare(string2); // -1
string2.localeCompare(string1); // 1
string2.localeCompare(“JavaScript”); // 0

string comparing

3. Changing the case

There may be some instances where we may need to change the case of the strings before proceeding further. This is especially required when we want to avoid the problem with the cases that we discussed above. I want to compare the strings, but with their alphabetical order regardless of their cases. JavaScript provides me with the facility to change the case of the string.

a. toLowerCase()

This method converts the given string into a lowercase string.

b. toUpperCase()

It converts the string provided into an uppercase string.

The above code returns the expected value after changing case before comparison. You should always use these two methods before comparing strings. Execute the following statements in your browser console to test these methods:

str1 = string1.toLowerCase() // “hello datatflair”
str2 = string2.toLowerCase() // “javascript”
string1 < string2 // false
str1 < str2 // true

string case

4. Altering strings

These methods manipulate the strings in the script. Since Strings are immutable in JavaScript, we cannot alter the original string, but these methods allow us to create new strings.

a. concat()

The concat() method in JavaScript concatenates (joins) two or more strings and returns the new string.

b. toString()

This method converts the argument passed (object, numbers, etc) to a String object representing the particular data type.

c. trim()

It trims i.e. removes all the whitespaces in the string, except for those between the non-empty characters.

d. valueOf()

It returns the primitive value equivalent to the specified object. The code below implements the methods above to perform string operations:

Note – The value of string1 is “Hello”, string2 is “ DataFlair ” and the value of num is 54.

Wait! You can’t move ahead before exploring our most trending blog on JavaScript Data Types.

string1.concat(" DataFlair!") // "Hello DataFlair!"
num.toString() // "54"
string2.trim() // "DataFlair"
string1.valueOf() // "Hello"

string alter

5. Playing with substrings

A substring is a set of characters, combined in a way that they are a part of the string. There are various methods in JavaScript, some of them listed below, to obtain a substring.

a. substring()

It extracts the desired section of the string, between the two indexes provided, and returns a new string.

b. substr()

This method returns the characters as a string starting from the specified index through the specified number of characters.

c. split()

This splits a String object into an array of strings, separated as substrings.

d. replace()

This method finds a substring in the regular expression or string and replaces it with a new substring.

Use the following code in your console:

string.substring(0, 9) // "DataFlair"
string.substr(12, 10) // "JavaScript"
string.split() // ["DataFlair's JavaScript Tutorial"]
string.replace("JavaScript", "String") // "DataFlair's String Tutorial"

substring

Summary

Here we conclude our tutorial on JavaScript Strings. In this article, we took a brief look at what JavaScript Strings are. Also, we discussed the syntax of creating a string, along with the different methods of String objects. Make sure you further practice all the methods and codes in your console too.

Next, you must go through our article on JavaScript Boolean

If you have any queries related to JavaScript Strings, do share with us through the comments.

Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *