Programming Language
JavaScript
String
JavaScript String

Complete Understanding Strings in JavaScript

Strings are fundamental in JavaScript, used to represent and manipulate text. This article will cover various aspects of strings, including creation, manipulation, and the different methods available.

Character Access

Accessing Characters

In JavaScript, strings are indexed, and you can access individual characters using bracket notation or methods:

  • Bracket Notation:
const str = 'Hello';
console.log(str[0]); // 'H'
  • charAt() Method:
console.log(str.charAt(1)); // 'e'

Print Each Character of a String

  • To print each character of a string, you can loop through the string:
const str = 'Hello';
for (let i = 0; i < str.length; i++) {
  console.log(str[i]);
}

Comparing Strings

  • Strings can be compared using standard comparison operators (==, ===, <, >, etc.):
const str1 = 'apple';
const str2 = 'banana';
 
console.log(str1 < str2); // true

Creating Strings

Using String Literals

You can create strings using single quotes, double quotes, or template literals:

  • Single Quotes:
const str1 = 'Hello';
  • Double Quotes:
 
  • Template Literals:
const name = 'Alice';
const str3 = `Hello, ${name}!`;

Primitive String vs. String Object

  • Primitive String:
const primitiveStr = 'Hello';
  • String Object:
const objectStr = new String('Hello');

Note: Primitive strings are more commonly used. String objects should be avoided for general string manipulation due to their added complexity.

String Coercion

JavaScript automatically converts non-string values to strings in many situations, such as when concatenating with a string:

Primitive Types:

  • undefined converts to the string "undefined".
  • null converts to the string "null".
  • true converts to "true" and false converts to "false".
  • Numbers are converted to strings using the same algorithm as toString(10).
  • BigInt values are also converted using toString(10).
console.log(String(undefined)); // 'undefined'
console.log(String(null));      // 'null'
console.log(String(true));      // 'true'
console.log(String(123));       // '123'
console.log(String(10n));       // '10'

Symbols:

Symbols cannot be directly converted to strings and will throw a TypeError if you attempt to use them in a string context.

const sym = Symbol('description');
// console.log(String(sym)); // Throws TypeError

Objects:

Objects are converted to strings by first converting them to a primitive using their Symbol.toPrimitive(), toString(), and valueOf() methods in that order. The resulting primitive is then converted to a string.

const obj = {
  toString() {
    return 'object';
  }
};
console.log(String(obj)); // 'object'

UTF-16 Characters, Unicode Code Points, and Grapheme Clusters

JavaScript strings are encoded in UTF-16. Each character in a string is a sequence of one or two 16-bit code units:

  • Unicode Code Points: Use String.fromCodePoint() to create a string from Unicode code points.
const smiley = String.fromCodePoint(0x1F600);
console.log(smiley); // 😀
 
  • Grapheme Clusters: Combining multiple code units to represent a single visual character.

Single and Double Quotes vs. Template Literals

  • Single and Double Quotes: Used for simple string literals.
const singleQuote = 'Hello';
const doubleQuote = "World";
  • Template Literals: Use backticks (`) and allow for multi-line strings and embedded expressions.
const name = 'Alice';
const greeting = `Hello, ${name}!`;

Passing Dynamic Data to Strings

Dynamic Data in Usual Strings

Concatenate strings with variables using the + operator:

const name = 'Alice';
const greeting = 'Hello, ' + name + '!';

Template Literals for Dynamic Data

  • Template literals provide a more readable and convenient way to embed expressions:
const age = 30;
const message = `I am ${age} years old.`;

String Methods

String length

Returns the number of characters in the string.

const str = 'Hello';
console.log(str.length); // 5

String charAt()

Returns the character at a specified index.

 

String charCodeAt()

Returns the Unicode value of the character at a specified index.

console.log(str.charCodeAt(0)); // 72 (ASCII code for 'H')

String at()

Returns the character at a specified index, allowing for negative indices.

console.log(str.at(1)); // 'e'

String [ ]

Accesses a character at a specified index.

console.log(str[1]); // 'e'

String slice()

Extracts a section of the string and returns it as a new string.

console.log(str.slice(1, 4)); // 'ell'

String substring()

Returns a part of the string between two indices.

console.log(str.substring(1, 4)); // 'ell'

String substr()

Returns a substring starting from a specified index and length.

console.log(str.substr(1, 3)); // 'ell'

String toUpperCase()

Converts all characters in the string to uppercase.

console.log(str.toUpperCase()); // 'HELLO'

String toLowerCase()

Converts all characters in the string to lowercase.

console.log(str.toLowerCase()); // 'hello'

String concat()

Combines two or more strings into one.

console.log(str.concat(' World')); // 'Hello World'

String trim()

Removes whitespace from both ends of the string.

const paddedStr = '   Hello   ';
console.log(paddedStr.trim()); // 'Hello'

String trimStart()

Removes whitespace from the beginning of the string.

console.log(paddedStr.trimStart()); // 'Hello   '

String trimEnd()

Removes whitespace from the end of the string.

console.log(paddedStr.trimEnd()); // '   Hello'

String padStart()

Removes whitespace from the end of the string.

console.log('5'.padStart(2, '0')); // '05'

String padEnd()

Pads the string with another string until it reaches a specified length, from the end.

console.log('5'.padEnd(2, '0')); // '50'

String repeat()

Repeats the string a specified number of times.

console.log('Hello'.repeat(3)); // 'HelloHelloHello'

String replace()

Replaces the first occurrence of a specified value with another value.

const text = 'Hello World';
console.log(text.replace('World', 'Universe')); // 'Hello Universe'

String replaceAll()

Replaces all occurrences of a specified value with another value.

const text = 'Hello World World';
console.log(text.replaceAll('World', 'Universe')); // 'Hello Universe Universe'

String split()

Splits the string into an array of substrings based on a separator.

const text = 'Hello World';
console.log(text.split(' ')); // ['Hello', 'World']

String indexOf()

Returns the index of the first occurrence of a specified value.

console.log(text.indexOf('World')); // 6

String lastIndexOf()

Returns the index of the last occurrence of a specified value.

console.log(text.lastIndexOf('World')); // 6

String search()

Searches for a specified value using a regular expression and returns its index.

console.log(text.search('World')); // 6

String match()

Finds matches for a regular expression in the string and returns an array.

console.log(text.match(/World/)); // ['World']

String matchAll()

Returns an iterator of all matches for a regular expression in the string.

console.log(text.matchAll(/World/g)); // [Array(1)]

String includes()

Checks if a specified value is found in the string.

console.log(text.includes('World')); // true

String startsWith()

Checks if the string starts with a specified value.

console.log(text.startsWith('Hello')); // true

String endsWith()

Checks if the string ends with a specified value.

console.log(text.endsWith('World')); // true

Conclusion

Strings in JavaScript are a powerful way to work with text. With various methods and features like template literals, string coercion, and character access, you can easily manipulate and format text to suit your needs. Understanding these basics helps you handle strings more effectively in your code.

  • Character Access: Strings are sequences of characters, and you can access individual characters using their index or methods.

  • Comparing Strings: You can compare strings using standard comparison operators to determine if they are equal or which one comes first lexicographically.

  • Creating Strings: Strings can be created using single quotes, double quotes, or backticks for template literals.

  • Primitive vs. String Object: JavaScript strings are primitives, but you can also create String objects. The primitive string is more common and efficient.

  • String Coercion: JavaScript automatically converts other types of values into strings in various contexts. This includes primitive types, objects, and symbols.

  • String Methods: JavaScript provides a variety of methods to manipulate strings, including:

    • charAt(), charCodeAt(), and at() for character access.
    • slice(), substring(), and substr() for extracting parts of strings.
    • toUpperCase(), toLowerCase() for case conversion.
    • concat(), trim(), padStart(), padEnd() for modifying strings.
    • replace(), replaceAll(), split(), indexOf(), lastIndexOf(), search(), match(), includes(), startsWith(), endsWith() for searching and comparing strings.