Hamburger Icon

How to work with strings in JavaScript

In this guide, you’ll explore the basics of working with strings in JavaScript so you can build dynamic and interactive web applications.

Apr 7, 2025 • 5 Minute Read

Please set an alt value for this image...
  • Software Development

Programming languages support various types of data, including integers, characters, Boolean, strings, and more. Data types inform a compiler or interpreter how a developer is intending to use the data in a script or application. It is fundamental for developers to understand the data types used by the language they are working with and how to use those data types. 

Strings are a core data type in JavaScript, and they are used to represent text. Working with strings is an essential skill for any JavaScript developer, as strings are used in various aspects of web development, from handling user input to manipulating and displaying data on web pages. In this guide, we'll explore the basics of working with strings in JavaScript to help you on your journey learning JavaScript.

What are strings in JavaScript?

In JavaScript, a string is a data type used to represent text. Whether it's a single character or an entire document, strings allow you to work with textual data.

Why work with strings?

Strings are a fundamental part of web development. They're used in various aspects, from handling user input to manipulating and displaying data on web pages. Understanding how to work with strings is essential for effective JavaScript programming.

How to declare a string in JavaScript

Declaring a string in JavaScript means defining a variable that will hold a string value. To declare a string variable in JavaScript, you use one of the following keywords: var, let, or const. Here's a basic example of declaring a string using let:

      let greeting = 'Hi, there!';
console.log(greeting); // Outputs: "Hi, there!"

    

In the above example:

  • let is the keyword used to declare the variable

  • greeting is the name of the variable

  • = is the assignment operator used to assign a value to the variable

  • "'Hi, there!" is the string value assigned to the variable. It's enclosed in single quotes, which is one way to create a string in JavaScript

After declaring a string variable, you can use it throughout your JavaScript code for various purposes, such as displaying text, manipulating data, or processing user input. Declaring a string allows you to work with textual data within your JavaScript code.

How to create strings in JavaScript

JavaScript provides multiple ways to create strings.

Single quotes

Example:

      let singleQuotes = 'This is a string using single quotes.'; 
    

Double quotes

Example:

      let doubleQuotes = "This is a string using double quotes."; 
    

Backticks (Template literals)

Backticks are especially useful for creating strings with embedded variables or expressions.

Example:

      let name = 'John'; let greeting = `Hello, ${name}!`; // Results in: "Hello, John!" 
    

String Properties and Methods

JavaScript offers several properties and methods to manipulate strings effectively.

Properties

length

Returns the number of characters in a string.

Example:

      let str = 'Hello, World!'; console.log(str.length); // Outputs: 13 
    

Methods

charAt(index)

Returns the character at the specified index in the string.

Example:

      let str = 'JavaScript'; console.log(str.charAt(2)); // Outputs: "v" 
    
concat(string2, string3, ...)

Combines one or more strings and returns a new string.

Example:

      let str1 = 'Hello, '; let str2 = 'World!'; let result = str1.concat(str2); console.log(result); // Outputs: "Hello, World!" 
    
indexOf(substring)

Returns the index of the first occurrence of a substring within a string. Returns -1 if the substring is not found.

Example:

      let str = 'JavaScript is fun.'; console.log(str.indexOf('is')); // Outputs: 12 
    
slice(start, end)

Extracts a portion of the string and returns it as a new string. The end parameter is optional.

Example:

      let str = 'JavaScript'; console.log(str.slice(0, 4)); // Outputs: "Java" 
    
toUpperCase() and toLowerCase()

Converts the string to uppercase or lowercase, respectively.

Example:

      let str = 'JavaScript'; console.log(str.toUpperCase()); // Outputs: "JAVASCRIPT" console.log(str.toLowerCase()); // Outputs: "javascript" 
    
replace(oldSubstr, newSubstr)

Replaces the first occurrence of oldSubstr with newSubstr and returns a new string.

Example:

      let str = 'Hello, World!'; let newStr = str.replace('World', 'JavaScript'); console.log(newStr); // Outputs: "Hello, JavaScript!" 
    
split(separator)

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

Example:

      let str = 'apple,banana,orange'; let fruits = str.split(','); console.log(fruits); // Outputs: ["apple", "banana", "orange"] 
    
trim()

Removes whitespace (spaces, tabs, and line breaks) from both ends of a string.

Example:

      let str = ' Hello, World! '; let trimmed = str.trim(); console.log(trimmed); // Outputs: "Hello, World!" 
    

String interpolation with template literals

Template literals (created using backticks) allow you to interpolate variables and expressions directly into strings, enhancing readability and convenience.

Embedding variables

Example:

      let name = 'Tom'; let age = 25; let message = `My name is ${name} and I am ${age} years old.`; console.log(message); // Outputs: "My name is Tom and I am 25 years old." 
    

Expressions inside strings

You can include expressions within template literals for dynamic content.

Multiline strings

Multiline strings in JavaScript refer to strings that span multiple lines of code. In JavaScript, you can create multiline strings using either template literals (introduced in ECMAScript 2015, also known as ES6) or by concatenating multiple strings together. Template literals are the preferred method for creating multiline strings, as they offer a more concise and readable way to do so.

Template literals use backticks (`) to define multiline strings. Here's an example:

      let multilineString = `
  This is a multiline string.
  It spans multiple lines.
  You can include line breaks without escaping.
  Template literals are very convenient!
`;
console.log(multilineString);

    

Conclusion

Congrats, you made it to the end of this guide! You are one step closer to building up your JavaScript expertise and meeting your goal, whatever it might be.

Working with strings in JavaScript is a fundamental skill that every JavaScript developer should have. By understanding string properties, methods, and template literals, you can manipulate, extract, and modify text to build dynamic and interactive web applications. As you continue to develop your JavaScript skills, exploring more advanced string manipulation techniques will become crucial for creating powerful and user-friendly web applications.

 

Steve Buchanan

Steve B.

Steve Buchanan is a Principal PM Manager with a leading global tech giant focused on improving the cloud. He is a Pluralsight author, the author of eight technical books, Onalytica's Who’s Who in Cloud?-top 50, and a former 10-time Microsoft MVP. He has presented at tech events, including, DevOps Days, Open Source North, Midwest Management Summit (MMS), Microsoft Ignite, BITCon, Experts Live Europe, OSCON, Inside Azure management, keynote at Minnebar 18, and user groups. He has been a guest on over a dozen podcasts and has been featured in several publications including the Star Tribune (the 5th largest newspaper in the US). He stays active in the technical community and enjoys blogging about his adventures in the world of IT at www.buchatech.com

More about this author