JavaScript String

Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

Learn via video course

Javascript Course - Mastering the Fundamentals
Javascript Course - Mastering the Fundamentals
By Mrinal Bhattacharya
Free
star4.8
Enrolled: 1000
Javascript Course - Mastering the Fundamentals
Javascript Course - Mastering the Fundamentals
Mrinal Bhattacharya
Free
4.8
icon_usercirclecheck-01Enrolled: 1000
Start Learning

Overview

The string is a primitive data type in javascript. Strings in javascript are used to store textual forms of data such as words, sentences, paragraphs, etc. Strings in javascript should be enclosed within single ticks or double ticks. Strings in javascript follow 0-based indexing.

Scope

In this article,

  • We'll learn about strings in javascript
  • It's a declaration, types, etc.
  • Also, We'll learn how to manipulate strings in javascript using different methods.

Ways to Create a String in JavaScript

Strings in Javascript can be created by two methods. Strings in Javascript can be created:

  • as primitives from string literals
  • as object using string() constructor

Creating strings as primitives:

Strings in Javascript can be created by enclosing the string text within single ticks (' '), or double ticks (" "), or backticks (\) This string is then assigned to a constant or variable.

Syntax

Here, str1 is assigned a string primitive enclosed within double ticks, str2 is assigned a string primitive enclosed within single ticks, and str3 is assigned a string primitive enclosed within backticks.

Note: The string created using backticks is known as template literal.

Creating strings as an object

Strings in javascript can be created by calling the String() constructor with the string as the parameter. The String() constructor is called using the new keyword and the value is assigned to a variable or constructor.

Syntax:

Here, the str4 will be assigned the string value as an object.

Ways to Access Individual Characters in a String

Strings in javascript follow 0-based indexing, i.e., the first character of the string is considered as the 0th character, the second character of the string is considered as the 1st character, and so on. For e.g., if we have string "abc", the a is the 0th character, b is the 1st character, and c is the 2nd character.

Thus in order to access an individual character of the string, we need to call the string along with the character index.

There are two ways to access the string character with an index:

By using charAt() method:

The charAt() method returns a new string consisting of the single UTF-16 code unit located at the specified offset into the string.

We can access the individual character of strings in javascript by calling the charAt() method along with string using the . operator and passing the index as the parameter to the charAt() method.

Syntax

str is the string whose characters are we accessing, and the index is the index values of the character that we are accessing.

Example

In the above example, the str.charAt(0) returns the character at 0th index and returns J. Similarly, the str.charAt(5) returns the character at 5th index and returns c.

By using Bracket Notation:

We can access individual characters in javascript strings using large brackets ([ ]). In this method, the string is treated as an array-like object, and the index of the character is passed within the brackets.

Syntax

str is the string whose characters are we accessing and the index is the index values of the character that we are accessing.

Example

In the above example, the str[0] returns the character at the 0th index and returns J. Similarly, the str.[5] returns the character at the 5th index and returns c.

Comparing Strings

The strings in javascript are compared in the lexicographical order, or in layman's terms the strings in javascript are compared in the dictionary order, i.e. if we have two strings str1 and str2 and str1 is placed before str2 in the dictionary then str2 is considered to be greater than str1.

Note: The comparison in the javascript strings is considered to be roughly equivalent to the dictionary order and not the same.

For example, the letter "A" is not equal to the letter "a", but the letter "a" is greater than "A" because, in the internal encoding table that strings in javascript use (Unicode), a lowercase character has a greater index than an uppercase character.

Strings in Javascript are compared by two methods:

By using localeCompare() method

The localeCompare() is a javascript method inherited by the string instances. It returns a number indicating whether a reference string comes before, or after, or is the same as the given string in sort order.

Note: It is primarily used to compare strings with non-ASCII characters.

By using less-than and greater-than operators

Strings in javascript can also be compared using comparison operators. The operator is placed between two strings and it compares the strings lexicographically and returns true if the expression is true otherwise returns false.

Syntax:

Here string1 and string2 are respective strings to be compared and op is the comparison operator (it could be > or < or ==).

Return value

It returns boolean value true if the expression is correct otherwise it returns false.

Example

In the above example, 'cat' > 'Bat' outputs true as lexicographically 'cat' > 'Bat'. Similarly, 'Zebra' < 'Xerox' outputs false as lexicographically 'Zebra' > 'Xerox'

String Primitives and String Objects

Following is a tabular comparison of String Primitives and String Objects:

String primitivesString objects
String primitives are primitive data types in Javascript.String objects wrap primitive data types to create an object.
String primitives are created by using single ticks, double ticks, or backticks.String objects are created by calling the String() constructor.
String primitives type is a sequence of 16-bit UTF-16 units.String Object is a built-in object with its internal Class property set to "String" and its internal Value property set to a value of the String

Long Literal Strings

Sometimes, we may have to write code that has strings that are very large. This may cause alignment issues or may take too much horizontal space in our editor, thus making our code messy.

To tackle this issue, strings in javascript can be broken down such that it has lines that go on endlessly, or we can wrap the strings in javascript at the whim of our code ide. The strings in javascript are broken into multiple lines without affecting the actual string contents.

There are two ways to achieve this in javascript:

By using an operator to append multiple strings together

We can break long strings in javascript into multiple shorter strings and append them using the + operator.

Example

By using the backslash character

We can also break the string into multiple lines using backslashes (\). The string would appear as a whole in the output.

Example

Constructor

The String() constructor in javascript is used to create a new string object. It can be called both as a constructor (using the new keyword) or as a function.

When called a constructor, the String() constructor converts the passed value to a string object.

When called as a function, the String() converts the passed value to a primitive string.

Syntax

Parameters

  • val: is anything that is to be converted to the string.

Example

In the above example, the new String(num) is called as a constructor, thus returns [String: '12345'] object, whereas the String(num) is called as a function, thus returns 12345 string.

Static Methods

Static Methods in javascript are the methods that are defined in the class itself. Static methods cannot be called an object. Static methods in javascript are often utility functions.

There are majorly three static methods in strings in javascript:

String.fromCharCode()

The String.fromCharCode() is used to create a string from a sequence of Unicode values.

Syntax:

Parameters

  • a, b, ..., x: The parameters are a sequence of numbers that are UTF-16 code units. It ranges is between 0 and 65535 (0xFFFF). Numbers greater than 0xFFFF are truncated. No validity checks are performed.

Return value:

A string of length N consisting of the N specified UTF-16 code units.

Example:

Explanation of the example:

In the above example, the first input is 68, 69, 70, which are the UTF characters for D, E, and F, thus the fromCharCode() method converts them and returns as a string. Similarly, the second input is 0x2014, which is the UTF character for _, thus the fromCharCode() method converts it and returns as a string.

String.fromCodePoint()

The String.fromCodePoint() is used to create a string from a sequence of Unicode points.

Syntax:

Parameters:

  • a, b, ..., x: The parameters represent the sequence of code points.

It throws a Range Error if the parameter passed is an invalid Unicode code point.

Return value:

A string is created by using the specified sequence of code points.

Example:

Explanation of the example:

In the above example, the first input is 42, which is the Unicode character for *, thus the fromCodePoint() method converts it and returns as a string. Similarly, the second input is 67, 89, which are the Unicode characters for C, Y, thus the fromCodePoint() method converts them and returns as a string.

String.raw()

The String.raw() method is used to get the raw string form of template literals, i.e, substitutions.

Syntax:

Parameters

  • callSite: is a well-formed template call site object.
  • ...substitutions: It contains substitution values.
  • templateString: It consists template literals. The literals could come with substitutions.

Return value:

It returns a raw string form of a given template literal.

Example:

Explanation of the example:

In the above example, the string does not skip the '\n' because of the String.raw method.

JavaScript String Methods

MethodDescription
charAt()Finds the character present at a particular index in the string.
concat()Concatenates the string arguments.
indexOf()returns the index of the first occurrence of the passed value.
lastIndexOf()returns the index of the last occurrence of the passed value.
toLowerCase()converts all the characters of the string into lowercase letters.
toUpperCase()converts all the characters of the string into uppercase letters.
split()divides the given string into an ordered list of substrings.
trim()removes additional spaces around the string.
toString()returns a string object as a string.
substring()extracts the characters between two indices of a string and returns a substring.
slice()extracts a section of a string and returns it as a new string, without modifying the original string.

JavaScript String charAt() Method

The JavaScript string charAt() method is used to find the character present at a particular index in the string.

Syntax:

Here, str is the string on which we are applying the charAt() method.

Parameters

  • ind: It is the index value of the character that we want to access. It should be between 0 and str.length - 1 (str.length is the length of the string).

Return value:

A string representing the character at the specified index.

Note: If index is out of range, the charAt() method returns an empty string.

Example:

In the above example, the str.charAt(2) will return the item present at 2nd index, i.e. v.

JavaScript String concat() Method

The concat() method in javascript is used to concatenate the string arguments such that the resultant string is the concatenation of all the strings.

Syntax:

str is the string with which the arguments are to be concatenated.

Parameters

  • a, b, ..., z: on or more strings that are to be concatenated with str.

Return value:

A new string containing the combined text of the strings provided in the argument.

Example:

In the above example, the str.concat() will concatenate all the argument strings into the str and return a combined string.

JavaScript String indexOf() Method

The indexOf() method takes a string value and returns the index of the first occurrence of the passed value in the calling string.

Syntax:

str is the string within which the argument will be searched

Parameters

  • val: It specifies the string value that is to be searched for in the str.
  • index (optional): By default the indexOf() method starts looking for the val from the index 0. This parameter is used to specify the starting index for the lookup.

Return value:

It returns a number which is the index of the first appearance of val. If val is not present in the string, then it returns -1.

Example:

In the above example, the str.indexOf('s') looks up for the first appearance of string s and returns it's index. Similarly, the str.indexOf('Z') looks up for the first appearance of string Z, since Z is not present in the string, so it returns -1.

JavaScript String lastIndexOf() Method

The lastIndexOf() method takes a string value and returns the index of the last occurrence of the passed value in the calling string.

Syntax:

str is the string within which the argument will be searched

Parameters

  • val: It specifies the string value that is to be searched for in the str.
  • index (optional): By default the indexOf() method starts looking for the val from the index 0 and traverse till the end to return the last appearance of the val. This parameter is used to specify the index till where the lookup should happen (or an index after which the lookup should stop).

Return value:

It returns a number which is the index of the last appearance of val. If val is not present in the string, then it returns -1.

Example:

In the above example, the str.lastIndexOf('s') looks up for the last appearance of string s and returns its the index. Similarly, the str.lastIndexOf('Z') looks up for the last appearance of string Z, since Z is not present in the string so it returns -1.

JavaScript String toLowerCase() Method

The toLowerCase() method in javascript string converts all the characters of the string into lowercase letters.

Note: The toLowerCase() method doesn't affect the value of the original str but returns a new string with lowercase characters.

Syntax:

Return value:

It returns a new string with all the characters converted into lowercase letters.

Example:

In the above example, the string str has mixed case characters. The str.toLowerCase() returns a new string where all the characters of str are in lowercase.

JavaScript String toUpperCase() Method

The toUpperCase() method in javascript string converts all the characters of the string into uppercase letters.

Note: The toUpperCase() method doesn't affect the value of the original str but returns a new string with lowercase characters.

Syntax:

Return value:

It returns a new string with all the characters converted into uppercase letters.

Example:

In the above example, the string str has mixed case characters. The str.toUpperCase() returns a new string where all the characters of str are in uppercase.

JavaScript String split() method

The split() method in javascript is used to divide the given string into an ordered list of substrings.

The string division is based on a pattern, where the pattern is provided as the first parameter in the method's call.

Syntax:

Parameters

  • pattern (optional): The patterns define how the string split should occur. It could be a string or a regular expression.
  • limit (optional): It decides the number of substrings to be included in the array, i.e., once the resultant array has reached the limit, the string split stops. Its value should be positive.

Return value:

It returns an array of strings.

Example:

In the above example, the (str.split(' ') splits the strings at spaces. Similarly, str.split(' ', 2) splits the string at spaces, but the limit here is only 2, thus it returns only two elements in the array.

JavaScript String trim() method

The trim() method removes additional spaces around the string and returns a new string. The additional space could be spaces, tabs etc.

Note: The trim() method doesn't alter the original string but returns a new string.

Syntax:

Return value:

A new string with no extra spaces on either side.

Example:

JavaScript String toString() method

The toString() method returns a string object as a string.

Syntax:

Return value:

A string represents the calling object.

Example:

In the above example, the newStr is a string object in the form [String: 'Javascript']. The toString() method will change the newStr into a primitive string.

JavaScript String substring() method

The javascript substring() method is used to get a substring from a string. It extracts the characters between two indices of a string and returns a substring.

Syntax:

Parameters

  • begin: It defines the index of the starting character of the substring.
  • end (optional): It is the index of the first character of the string that should be excluded from the substring.

Return value:

A string containing a part of the parent string.

Example:

In the above example, the str.substring(3) takes an index and returns the substring that includes characters from that index till the end of the string. Similarly, the str.substring(3, 7) takes two indexes and returns a string that includes characters from the first index till the last (excluding the last).

JavaScript String slice() Method

The Javascript slice() method extracts a section of a string and returns it as a new string, without modifying the original string.

Syntax:

Parameters

  • begin: It defines the index of the starting character of the substring.
  • end (optional): It is the index of the first character of the string that should be excluded from the substring.

Note: The parameters of the slice() method can take negative values.

Return value:

A string containing a part of the parent string.

Example:

In the above example, the str.slice(3) takes an index and returns the substring that includes characters from that index till the end of the string. Similarly, the str.slice(3, 7) takes two indexes and returns a string that includes characters from the first index till the last (excluding the last).

Since the input in the str.slice(-2) method is negative, thus the slicing will start from str.length + begin i.e. 10 + (-2) which is equal to 8.

Instance Properties

A typical property declared in a class is an instance property in Javascript. Following are the instance properties of strings in javascript:

String.prototype.length

This is a read-only property that returns the length of the strings in javascript.

Note: If the string is empty, it returns 0.

Syntax:

Return value A number represents the length of the string.

Example:

In the above example, the str.length returns 10, as the length of string Javascript is 10.

Instance Methods

Following are the instance methods of strings in javascript:

  • string.prototype.at(index): Returns the character (exactly one UTF-16 code unit) at the specified index. Accepts negative integers, which count back from the last string character.
  • string.prototype.charAt(index): Returns the character (exactly one UTF-16 code unit) at the specified index.

Browser Compatibility

Browser:ChromeEdgeInternet explorerOperaSafariFirefox
String1123311

If the version of the browser is mentioned, then it means that it is the minimum version of that browser required to support the string feature.

Conclusion

  • Strings in javascript are primitive data types used to store textual content.
  • Strings in javascript can be created either as primitives or objects.
  • Primitive strings are created using single ticks, double ticks, or backticks.
  • String objects are created by calling the String() constructor.
  • Strings in javascript follow 0-based indexing
  • Strings in javascript can be compare by using comparison operators or localeCompare() method.
  • Strings in javascript can be manipulated by using a set of methods.