JavaScript Strings: From Basics to Advanced

You are currently viewing JavaScript Strings: From Basics to Advanced

Understanding JavaScript strings is essential for any developer. Strings in JavaScript come with a rich set of properties and methods that allow for powerful text manipulation and searching. In this blog, we’ll dive deep into the various aspects of JavaScript strings, from basic concepts to advanced methods. We’ll cover string creation, escape characters, string methods, and string search functionalities, providing detailed examples along the way. We’ll also include potential interview questions to help you test your knowledge.

What is a String?

In JavaScript, a string is a sequence of characters enclosed in quotes. You can use single quotes ('), double quotes ("), or backticks (`) to create strings.

let singleQuoteString = 'Hello, World!';
let doubleQuoteString = "Hello, World!";
let backtickString = `Hello, World!`;
let name = 'JavaScript';
let message = `Hello, ${name}!`;
console.log(message); //output: Hello, JavaScript! 

Below are the important methods, escape characters, and string search functionalities you should know and why they are essential for effective string manipulation.

String Methods

MethodDescriptionExample
lengthReturns the length of a string.
let str = "JavaScript";

console.log(str.length); // Output: 10
charAt()Returns the character at a specified index. let str = "JavaScript"; console.log(str.charAt(0)); // Output: J
charCodeAt()Returns the Unicode of the character at a specified index. let str = "JavaScript"; console.log(str.charCodeAt(0)); // Output: 74
at()Returns the character at a specified index (supports negative indices).
let str = "JavaScript";

console.log(str.at(0)); // Output: J \n console.log(str.at(-1)); // Output: t
[]Accesses characters in a string using bracket notation.
let str = "JavaScript";

console.log(str[0]); // Output: J
slice()Extracts a part of a string and returns it as a new string.
let str = "JavaScript";

console.log(str.slice(0, 4)); // Output: Java
substring()Returns the part of the string between start and end indexes. let str = "JavaScript"; console.log(str.substring(4, 10)); // Output: Script
substr()Returns a portion of the string, starting at the specified index and extending for a given number of characters.
let str = "JavaScript";

console.log(str.substr(4, 6)); // Output: Script
toUpperCase()Converts a string to uppercase letters. let str = "JavaScript"; console.log(str.toUpperCase()); // Output: JAVASCRIPT
toLowerCase()Converts a string to lowercase letters. let str = "JavaScript"; console.log(str.toLowerCase()); // Output: javascript
concat()Joins two or more strings.
let str1 = "Java";

let str2 = "Script"; console.log(str1.concat(str2)); // Output: JavaScript
trim()Removes whitespace from both ends of a string. let str = " JavaScript "; console.log(str.trim()); // Output: JavaScript
trimStart()Removes whitespace from the beginning of a string. let str = " JavaScript "; console.log(str.trimStart()); // Output: JavaScript
trimEnd()Removes whitespace from the end of a string. let str = " JavaScript "; console.log(str.trimEnd()); // Output: JavaScript
padStart()Pads the current string with another string until the resulting string reaches the given length (from the start).
let str = "5";

console.log(str.padStart(3, "0")); // Output: 005
padEnd()Pads the current string with another string until the resulting string reaches the given length (from the end).
let str = "5";

console.log(str.padEnd(3, "0")); // Output: 500
repeat()Returns a new string with a specified number of copies of the original string.
let str = "Java";

console.log(str.repeat(3)); // Output: JavaJavaJava
replace()Searches a string(first occurrence) for a specified value or a regular expression and returns a new string where the specified values are replaced.
If you replace a value, only the first instance will be replaced. To replace all instances, use a regular expression with the g modifier set.

let str = "JavaScript is awesome";

let newStr = str.replace("awesome", "great");
console.log(newStr); // Output: JavaScript is great


let text = "Visit Microsoft! ,Visit Microsoft!";
let result = text.replace("Microsoft", "MindShareHub"); //Visit MindShareHub! ,Visit Microsoft!";


result
= text.replace(/Microsoft/g, "MindShareHub");
//Visit MindShareHub! ,Visit MindShareHub!

replaceAll()Returns a new string with all matches of a pattern replaced by a replacement.
let str = "JavaScript is awesome. JavaScript is great.";

let newStr = str.replaceAll("JavaScript", "JS");
console.log(newStr); // Output: JS is awesome. JS is great.


split()Splits a string into an array of substrings.
let str = "JavaScript is awesome";

let arr = str.split(" ");
console.log(arr); // Output: ["JavaScript", "is", "awesome"]

Escape Characters

Escape CharacterDescriptionExample
\'Inserts a single quote in a string.let str = 'It\'s a beautiful day!';
//output: It's a beautiful day!
\"Inserts a double quote in a string.let str = "She said, \"Hello!\"";
//output: She said, "Hello!"
\\Inserts a backslash in a string.let str = "This is a backslash: \\";
//output: This is a backslash: \

String Search

MethodDescriptionExample
indexOf()Returns the index of the first occurrence of the specified value. Returns -1 if not found.let str = "Hello, World!"; console.log(str.indexOf("World"));
//Output: 7
lastIndexOf()Returns the index of the last occurrence of the specified value. Returns -1 if not found.let str = "Hello, World! World!"; console.log(str.lastIndexOf("World"));
//Output: 13
Both methods accept a second parameter as the starting position for the search:let text = "Please locate where 'locate' occurs!";
let index = text.indexOf("locate", 15);


search()Searches for a match between a regular expression and the string. Returns the index of the match or -1 if not found.let str = "Hello, World!"; console.log(str.search(/World/));
//Output: 7
match()Retrieves the result of matching a string against a regular expression. Returns an array of matches or null if no match.let str = "Hello, World!"; console.log(str.match(/World/));
//Output: ['World']
matchAll()Returns an iterator of all matches of a regular expression in the string.let str = "Hello, World! World!"; let matches = str.matchAll(/World/g);
for (const match of matches) {
console.log(match);
}
//Output: [ 'World', index: 7, input: 'Hello, World! World!', groups: undefined ]
[ 'World', index: 13, input: 'Hello, World! World!', groups: undefined ]
includes()Checks if the string contains the specified value. Returns true or false.let str = "Hello, World!"; console.log(str.includes("World"));
//Output: true
startsWith()Checks if the string starts with the specified value.let str = "Hello, World!"; console.log(str.startsWith("Hello"));
//Output: true
endsWith()Checks if the string ends with the specified value.let str = "Hello, World!"; console.log(str.endsWith("World!"));
//Output: true

Are indexOf() and search() the same?

The two methods are NOT equal. These are the differences:

  • The search() method cannot take a second start position argument.
  • The indexOf() method cannot take powerful search values (regular expressions).

What is Template strings or Template literals?

Template strings, also known as template literals, are a feature in JavaScript that allows for easier and more readable string interpolation and multi-line strings. They are denoted by backticks (`) rather than single or double quotes.

Basic Syntax: Template literals are enclosed in backticks (`) and can contain placeholders indicated by the ${expression} syntax.

let name = "JavaScript"; 
let message = `Hello, my name is ${name}.`;
console.log(message); // Output: 'Hello, my name is JavaScript.'

Multi-line Strings: Template literals allow for multi-line strings without the need for escape sequences.

let multiLineString = `This is a string
that spans multiple
lines.`;
console.log(multiLineString);
// Output:
// This is a string
// that spans multiple
// lines.

String Interpolation: You can embed expressions inside template literals. The expressions are evaluated and included in the resulting string.

let x = 10;
let y = 20;
let sum = `The sum of ${x} and ${y} is ${x + y}.`;
console.log(sum); // Output: 'The sum of 10 and 20 is 30.'

Tagged Templates: Tagged templates allow you to parse template literals with a function. This can be useful for creating custom string processing or formatting.

function tag(strings, ...values) {
  console.log(strings);// ['Hello, my name is ', ' and I am ', ' years old.'],
  console.log(values);// ['Alice', 25]
  return strings.raw[0] + values[0] + strings.raw[1]+ values[1]  + strings.raw[2];
}

let name = "Alice";
let age = 25;
let result = tag`Hello, my name is ${name} and I am ${age} years old.`;
console.log(result); // Output: Hello, my name is Alice and I am 25 years old.

How do you convert the first letter of a string to uppercase?

function capitalizeFirstLetter(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}
let result = capitalizeFirstLetter("hello");
console.log(result); // Output: 'Hello'

How do you print numbers with commas as thousand separators?

let number = 1234567.89;
console.log(number.toLocaleString()); // Output: '1,234,567.89'

How do you create a specific number of copies of a string?

let str = "Hello";
let repeatedStr = str.repeat(4);
console.log(repeatedStr); // Output: 'HelloHelloHelloHello'

How to remove all line breaks from a string?

let stringWithLineBreaks = `This is a string
with line breaks
that need to be removed.`;
let cleanedString = stringWithLineBreaks.replace(/\n/g, ' ');
console.log(cleanedString); // Output: 'This is a string with line breaks that need to be removed.'

How to revers a string?

To reverse a string in JavaScript, you can use the following approach by combining various string and array methods. Here’s a step-by-step method to reverse a string:

  1. Convert the string to an array of characters.
  2. Reverse the array.
  3. Join the array back into a string.
function reverseString(str) {
  return str.split('').reverse().join('');
}

// Example usage
console.log(reverseString("hello Javascript")); // Output: tpircsavaJ olleh
console.log(reverseString("tpircsavaJ olleh")); // Output: hello Javascript

Count the Occurrences of a Character in a String

You can use the split method to split the string by the character and then check the length of the resulting array.

function countOccurrences(str, char) {
    return str.split(char).length - 1;
}

let str = "JavaScript is awesome";
console.log(countOccurrences(str, 'a')); // Output: 3

Check if Two Strings are Anagrams?

Anagrams are words or phrases formed by rearranging the letters of another word or phrase using all the original letters exactly once.

function areAnagrams(str1, str2) {
    let normalize = str => str.toLowerCase().split('').sort().join('');
    return normalize(str1) === normalize(str2);
}

console.log(areAnagrams("listen", "silent")); // Output: true
console.log(areAnagrams("hello", "world")); // Output: false

What will be the output?

QuestionOutputExplanation
console.log(‘hello’ – ‘world’);NaNSubtracting strings is not a valid operation in JavaScript, resulting in NaN
console.log(‘hello’ + ‘world’);helloworldUsing the + operator concatenates strings, producing the combined string ‘helloworld’.
You can share it on

Leave a Reply