JavaScript strings

Introduction

In JavaScript, a string is essentially an object that encompasses a group of characters, which can include letters, digits, symbols, and even special characters like '\b,' '\'.

,' '\\t,' '\\r,' and '\\"'.

Strings in programming can be enclosed in either single quotes (') or double quotes ("). This means that both 'some text' and "some text" are considered acceptable. For instance, various string examples include "greetings," "greetings universe," "456," "hello" combined with "world," and "hi\ there."

In JavaScript, there are two main methods for creating strings: you can opt to employ a string object (by making use of the new keyword) or you can simply utilize a string literal.

JavaScript String Methods

JavaScript String charAt Method

The charAt method in JavaScript is a useful function for retrieving a character located at a particular index within a string.

Syntax:

Example

str.charAt(ind)

In this scenario, the variable str represents the string being processed when invoking the charAt function.

Parameters:

ind: This is the index of the character you want to retrieve. Remember, it should be between 0 and str.length - 1 (where str.length is the total number of characters in the string).

Return value:

It provides a string that represents the character located at the specified index.

Note: If the index you provide is out of range, the charAt method will simply return an empty string.

Example

Example

let str = 'Javascript is a programming language';

console.log(str.charAt(2));

//output: v

Output:

In the provided example, calling str.charAt(2) will return the character found at the index position 2, which in this case is 'v'.

JavaScript String concat Method

The concat function in JavaScript is employed to combine string inputs, creating a fresh string that includes all the provided strings.

Syntax:

Example

str.concat(a)

str.concat(a, b)

str.concat(a, b, ... , z)

The variable labeled as str represents the string that will be concatenated with extra arguments.

Parameters:

  • a, b, ..., z: One or multiple strings that you wish to concatenate with str.

Return value:

A new string will be generated by combining the content from the strings you have supplied.

Example

Example

let str = 'Javascript is a programming language';

console.log(str.concat(', ', 'as well as one of the most used language.'));

//output: Javascript is a programming language, as well as one of the most used language.

Output:

In the given example, the str.concat function combines multiple strings provided as input into a unified string output.

JavaScript String indexOf Method

The indexOf function is used to search for a specific string value within a given string and returns the index of the first occurrence of the specified value within the string being searched.

Syntax:

Example

str.indexOf(val);

str.indexOf(val, index);

The str represents the string within which we will be looking for the parameter.

Parameters:

  • val: This is the string value you aim to locate within str.
  • index (optional): By default, the indexOf method begins its search for val at index 0.You can utilize this parameter to specify a different starting point for your search.

Return value:

The function returns a value representing the position of the first occurrence of val within the string. In case val is not present in the string, the function will return -1.

Example

Example

let str = 'Javascript is a programming language';

console.log(str.indexOf('s'));

//output: 4

console.log(str.indexOf('Z'));

//output: -1

Output:

In the given illustration, the function str.indexOf('s') is utilized to search for the initial occurrence of the character 's' within the string and returns its index. Likewise, if you were to employ str.indexOf('Z'), it would seek the first instance of 'Z'. As 'Z' is not found within the string, the function returns -1.

JavaScript String lastIndexOf Method

The lastIndexOf function accepts a string value as an argument and provides the position of the last appearance of that value within the string from which the function is called.

Syntax:

Example

str.indexOf(val);

str.indexOf(val, index);

Parameters:

  • val: This represents the string value you wish to locate within str.
  • index (optional): Typically, the indexOf method begins its search for val from the start, at index 0, and continues until the end to identify the last occurrence of val. This parameter enables you to specify a particular index to restrict the search area or to indicate an index after which the search should stop.

Return value:

The function returns the index of the final val occurrence. In case val cannot be located in the string, the function will output -1.

Example

Example

let str = 'Javascript is a programming language';

console.log(str.lastIndexOf('a'));

//output: 33

console.log(str.lastIndexOf('Z'));

//output: -1

Output:

Output

33

-1

In the method str.lastIndexOf('s'), it retrieves the final occurrence index of the character 's' within the specified string. In contrast, if you utilize str.lastIndexOf('Z'), it will provide the ultimate index of 'Z'. Given that 'Z' is absent in the provided string, the method will return -1 as the output value.

JavaScript String toLowerCase Method

The toLowerCase function in JavaScript is a simple method that converts all the characters within a string to lowercase.

Note: Invoking the toLowerCase method doesn't change the original string but provides you with an entirely different string with every character in the lowercase.

Syntax:

Example

str.toLowerCase();

Return value:

A fresh string will be provided where all characters are converted to lowercase in an orderly manner.

Example

Example

let str = 'JavaScript Is a proGraMMing language';

let newStr = str.toLowerCase();

console.log(newStr);

//output: javascript is a programming language

Output:

Output

javascript is a programming language

JavaScript String toUpperCase Method

Let's now explore the uppercase conversion functionality in JavaScript, known as the toUpperCase function. This useful function transforms all the characters in a string to uppercase.

Note: Invoking the `toUpperCase` method does not change the original `str`; it returns a new string that contains all the characters in upper case.

Syntax:

Example

str.toUpperCase();

Return value:

It produces a fresh string in which each character has been transformed into uppercase.

Example

Example

let str = 'JavaScript Is a proGraMMing language';

let newStr = str.toUpperCase();

console.log(newStr);

//output: JAVASCRIPT IS A PROGRAMMING LANGUAGE

Output:

Output

JAVASCRIPT IS A PROGRAMMING LANGUAGE

In the example provided, the variable str contains both lower and upper letters. When using the method str.toUpperCase, it returns a new string where all the characters of str are replaced with their upper letters.

JavaScript String split method

The function is utilized for dividing a string into an array of smaller substrings. The splitting mechanism is determined by a designated pattern supplied as the initial parameter in the function call.

Syntax:

Example

str.split();

str.split(pattern);

str.split(pattern, limit);

Parameters:

Format (optional): This indicates the manner in which the string is to be partitioned. It can be either a simple string or a regular expression.

The optional parameter "limit" determines the maximum number of substrings to be included in the resultant array. Once this limit is met, the splitting of the string will cease. It is important to note that the value assigned to this parameter should be a non-negative whole number.

Return value:

It generates an array of strings.

Example

Example

let str = 'JavaScript is a programming language';

console.log(str.split(' '));

//output: [ 'JavaSript', 'is', 'a', 'programming', 'language' ]

console.log(str.split(' ', 2));

//output: [ 'JavaScript', 'is' ]

Output:

In the example provided, the method (str.split(' ')) divides the strings at every space occurrence. However, when using str.split(' ', 2), the string is divided at spaces but with a constraint of 2, resulting in only two elements within the array that is produced.

Conclusion

To sum up, JavaScript strings are an inherent data type used for storing text. Strings can be generated as either primitive values or objects. You can indicate primitive strings using single quotes, double quotes, or backticks. Comparison operators or the localeCompare method can be utilized to compare JavaScript strings. There are various methods to manipulate JavaScript strings.

JavaScript String Methods

Methods Description
charAt() It provides the char value present at the specified index.
charCodeAt() It provides the Unicode value of a character present at the specified index.
concat() It provides a combination of two or more strings.
indexOf() It provides the position of a char value present in the given string.
lastIndexOf() It provides the position of a char value present in the given string by searching a character from the last position.
search() It searches a specified regular expression in a given string and returns its position if a match occurs.
match() It searches a specified regular expression in a given string and returns that regular expression if a match occurs.
replace() It replaces a given string with the specified replacement.
substr() It is used to fetch the part of the given string on the basis of the specified starting position and length.
substring() It is used to fetch the part of the given string on the basis of the specified index.
slice() It is used to fetch the part of the given string. It allows us to assign positive as well negative index.
toLowerCase() It converts the given string into lowercase letter.
toLocaleLowerCase() It converts the given string into lowercase letter on the basis of host?s current locale.
toUpperCase() It converts the given string into uppercase letter.
toLocaleUpperCase() It converts the given string into uppercase letter on the basis of host?s current locale.
toString() It provides a string representing the particular object.
valueOf() It provides the primitive value of string object.
split() It splits a string into substring array, then returns that newly created array.
trim() It trims the white space from the left and right side of the string.

Input Required

This code uses input(). Please provide values below: