Tutorials

JavaScript ES6 Strings

Key Takeaways

  • Strings in JavaScript can be created using single, double quotes or backticks (template literals).
  • ES6 brought new and more powerful methods for string manipulation, like `startsWith`, `endsWith`, and template literals.
  • Template literals offer easier multi-line strings and embedded expressions with interpolation.

Strings store a sequence of characters and are commonly used for holding text such as names or descriptions. In JavaScript, any text enclosed in either double or single quotes is recognized as a string.

let firstName = "John";
let lastName = 'Doe';

Defining Strings

Strings can be defined using simple quotes:

let firstName = "John";

You can also utilize the String() constructor to create a string object, though this is less commonly preferred:

let firstName = new String("John");

String Methods

The following are some of the vital methods the String object supports in JavaScript:

length

Returns the total number of characters in a string, including spaces:

let myString = "hello";

myString.length;

// returns 5

charAt()

Returns the character at the specified index:

let myString = "hello";

myString.charAt(2);

// returns 'l'

charCodeAt()

Returns a Unicode representation of the character at a given index:

let myString = "hello";

myString.charCodeAt(2);

// returns 108

concat()

Combines strings together:

let firstName = "John";
let lastName = " Doe";

firstName.concat(lastName);

// returns 'John Doe'

indexOf()

Finds the index of the first occurrence of a specified value, returning -1 if no match is found:

let firstName = "John";

firstName.indexOf('o');
// returns 1

firstName.indexOf('z');
// returns -1

lastIndexOf()

Similar to indexOf(), but returns the last occurrence of the specified value:

let fruit = "banana";

fruit.lastIndexOf('a');
// returns 5

fruit.lastIndexOf('z');
// returns -1

localeCompare()

Compares the order of a string argument to that of the string itself, with -1, 0, and 1 as the possible return values:

let myString = "hello world";

myString.localeCompare("goodbye");
// returns 1 (no match, "goodbye" comes before)

myString.localeCompare("zed");
// returns -1 (no match, "zed" comes after)

myString.localeCompare("hello world");
// returns 0 (exact match)

match()

Uses regular expressions to find matches, returning an array of all occurrences or null if none:

let fruit = 'banana';

fruit.match(/a/g);
// returns ['a','a','a']

fruit.match(/z/);
// returns null

replace()

Replaces characters in a string based on a regex or substring:

let myString = "hello world";

myString.replace(/l/g, "z");
// returns 'hezzo worzd'

myString.replace(/l/, "z");
// returns 'hezlo world'

Searches for a regex within the string, returning the index of the match or -1

let myString = "hello world";

myString.search(/world/);
// returns 6

myString.search(/zed/);
// returns -1

slice()

Returns a substring using specified start and end indexes:

let myString = "hello world";

myString.slice(0, 2);
// returns 'he'

myString.slice(2, 4);
// returns 'll'

split()

Splits a string into an array of substrings using a defined separator:

let myString = "hello world";

myString.split(" ");
// returns ['hello', 'world']

myString.split("l");
// returns ['he', '', 'o wor', 'd']

myString.split("l", 2);
// returns ['he', '']

substr()

Returns a substring based on a start position and a given length:

let myString = "hello world";

myString.substr(-1);
// returns 'd'

myString.substr(0, 5);
// returns 'hello'

myString.substr(2, 3);
// returns 'llo'

substring()

Returns a range of characters, with the second argument being an end index:

let myString = "hello world";

myString.substring(2, 3);
// returns 'l'

toLowerCase()

Converts all characters in the string to lowercase:

let myString = "Hello World";

myString.toLowerCase();
// returns 'hello world'

toUpperCase()

Converts all characters in the string to uppercase:

let myString = "Hello World";

myString.toUpperCase();
// returns 'HELLO WORLD'

valueOf()

Returns the primitive value of a string object:

let myString = "hello world";

myString.valueOf();
// returns 'hello world'

startsWith()

Checks if a string begins with the supplied argument. Optionally, a second parameter specifies where to start checking:

let myString = "hello world";

myString.startsWith('hel');
// returns true

myString.startsWith('el');
// returns false

myString.startsWith('el', 1);
// returns true

endsWith()

Checks if a string ends with the given argument, optionally specifying the length to consider:

let myString = "hello world";

myString.endsWith('world');
// returns true

myString.endsWith('world', 11);
// returns true

myString.endsWith('world', 10);
// returns false

includes()

Determines if a substring is within the string. Optionally, a start position can be specified:

let myString = "hello world";

myString.includes('world');
// returns true

myString.includes('world', 7);
// returns false

repeat()

Repeats the string a specified number of times:

let myString = "hello world";

myString.repeat(3);
// returns 'hello worldhello worldhello world'

Template Literals

ES6 introduces template literals, providing a way to embed expressions and define multi-line strings. Template literals utilize backticks (`) instead of quotes:

let myLiteral = `this is a literal`;

String Interpolation

Template literals allow expression embedding with interpolation placeholders:

let myAge = 30;
let myName = 'John';
let statement = `Hello, my name is ${myName} and I am ${myAge} years old.`;

console.log(statement);
// logs: 'Hello, my name is John and I am 30 years old.'

Use the ${} syntax to embed expressions within template literals.

Multiline Strings

Template literals also support multi-line string definitions effortlessly:

let myString = `This is a string that
spans multiple lines
stored as myString.`;

Other Methods

String.fromCodePoint()

Returns a new string based on provided Unicode code points:

let myString = String.fromCodePoint(102, 110);

console.log(myString);
// logs: 'fn'

String.raw()

The String.raw() method provides raw access to a template literal's content, meaning it does not escape backslashes:

let myString = `hello \world`;

console.log(myString);
// returns: 'hello \world'

Conclusion

Mastering string handling in JavaScript lets you dynamically manipulate text and embed expressions within code seamlessly. Strings are a fundamental tool for managing character data effectively in your programs.

FAQ

What are the advantages of using template literals?

Template literals introduce multi-line strings and make string interpolation much clearer and more maintainable than traditional string concatenation techniques.

It's better to use `let` and `const` for declaring variables, including strings, to ensure block-scoping and prevent re-declaration issues.

Are string objects necessary in modern JavaScript?

String objects created via `new String()` aren't recommended. Using primitive strings is more efficient and behaves as expected in comparisons and function calls.

Mastering the tech interviewWhat everyone is doing wrong in tech interviews