Flat Preloader Icon

String In JS

In JavaScript, a string is a sequence of characters stored as a single data type. Strings are widely used for representing text and are essential for working with textual data in JavaScript.

Definition:

  • A string in JavaScript is a primitive data type that represents a sequence of characters enclosed within single (') or double (") quotes. For example:

				
					let greeting = "Hello, world!";
let name = 'John Doe';

				
			

Characteristics:

  • Immutable: Strings in JavaScript are immutable, meaning once a string is created, its value cannot be changed. However, you can create a new string based on the original string’s value.

  • Unicode Support: JavaScript strings support Unicode characters, allowing you to work with characters from various languages and symbol sets.

  • Escape Sequences: Strings can include special characters and escape sequences, such as \n for newline, \t for tab, \\ for backslash, etc.

String Methods:

JavaScript provides a variety of built-in methods to manipulate and work with strings effectively. Some common string methods include:

  • length: Returns the length of the string.
  • charAt(index): Returns the character at the specified index.
  • concat(str1, str2, ...): Concatenates one or more strings with the original string.
  • indexOf(substring): Returns the index of the first occurrence of the specified substring within the string.
  • substring(startIndex, endIndex): Returns a new string containing characters from startIndex up to but not including endIndex.
  • slice(startIndex, endIndex): Returns a portion of the string, starting from startIndex up to but not including endIndex.
  • toUpperCase(): Converts the string to uppercase.
  • toLowerCase(): Converts the string to lowercase.
  • split(separator): Splits the string into an array of substrings based on the specified separator.

Example:

				
					let str = "Hello, world!";
console.log(str.length);
// Output: 13
console.log(str.charAt(0)); 
// Output: H
console.log(str.indexOf("world")); 
// Output: 7
console.log(str.toUpperCase());
// Output: HELLO, WORLD!
console.log(str.split(", ")); 
// Output: ["Hello", "world!"]