← Learning Hub
Intermediate

Strings and Template Literals

Text in JavaScript is a string. Strings come with many built-in methods - small tools you call with a dot.

A huge part of web programming is text: names typed into forms, search words, messages, product titles, addresses. You'll constantly need to clean it (trim spaces), compare it (ignoring capital letters), search inside it, and build new text from values. JavaScript's string methods cover all these jobs.

Example
const name = "  Terixto Shop  ";

console.log(name.trim());                // Output: Terixto Shop
console.log(name.trim().toUpperCase());  // Output: TERIXTO SHOP
console.log(name.trim().length);         // Output: 12
console.log("mango".includes("go"));     // Output: true
console.log("mango".startsWith("ma"));   // Output: true
console.log("a,b,c".split(","));         // Output: [ 'a', 'b', 'c' ]
console.log("Delhi".slice(0, 3));        // Output: Del
console.log("2026".padStart(6, "0"));    // Output: 002026
console.log("hi-hi".replaceAll("hi", "yo"));  // Output: yo-yo

Template literals

Use backticks `...` to put values straight into text with ${ }. They can also span several lines.

Before template literals, building text meant joining pieces with + and quotes - easy to get wrong with spaces and quote marks. Backticks make the final text easy to see in the code, and are how most modern JavaScript builds messages and even small pieces of HTML.

Example
const item = "Headphones";
const price = 1499;
const qty = 2;

const line = `${qty} x ${item} = ₹${price * qty}`;
console.log(line);   // Output: 2 x Headphones = ₹2998
Example
<!DOCTYPE html>
<html>
  <body>
    <pre id="out"></pre>
    <script>
      function show(...values) {
        document.getElementById("out").textContent += values.join(" ") + "\n";
      }
      const user = "Asha";
      const items = 3;
      show(`Hello ${user}, you have ${items} items in your cart.`);
      show("TERIXTO".toLowerCase());
      show("one two three".split(" ").length + " words");
      show("₹" + (1499).toLocaleString("en-IN"));
    </script>
  </body>
</html>
▶ Try it yourself

Numbers to text and back

Example
console.log(String(42) + "!");        // Output: 42!
console.log(Number("42") + 8);        // Output: 50
console.log(parseInt("15 items"));    // Output: 15
console.log((12.5).toFixed(2));       // Output: 12.50
console.log((123456.7).toLocaleString("en-IN"));  // Output: 1,23,456.7
Strings never change in place. Methods like toUpperCase() give you a new string, so save the result: name = name.trim();
Key points
  • Strings have methods like trim, toUpperCase, includes, slice, replace.
  • Template literals: `Total: ${price}`.
  • Strings never change in place - save the result.

📝 Test yourself

1. What does " hi ".trim() give?
2. Which quotes allow ${ } inside the text?
3. Fill in the method that breaks "a,b,c" into an array:
"a,b,c".(",")