JavaScript Strings Tutorial: Methods, Template Literals, and Runnable Examples

Learn strings from their delimiters and zero-based indexes through searching, cleaning, and coercion. Each example is runnable, including a complete input-to-key transformation.

KnowledgeGate Team

Exam prep & CS education

Updated 2 Sep 20265 min read

You can declare variables, but JavaScript strings may still surprise you. Quote styles look interchangeable, indexes invite off-by-one mistakes, methods seem to ignore your changes, and adding a number may produce text. Reliable string code depends on matching delimiters, tracking zero-based indexes, storing method results, and recognising when an operator coerces a value to text.

JavaScript strings: create values with single, double, and backtick quotes

A string is a primitive value that represents a sequence of text characters. JavaScript accepts single quotes, double quotes, and backticks:

const platform = 'KnowledgeGate';
const language = "JavaScript";
const lesson = `Strings`;

console.log(typeof language); // "string"
console.log(platform.length); // 13

All three variables hold string primitives. The opening and closing delimiter must match, but you can choose a delimiter that makes embedded punctuation easier to read.

const notice = "Asha's lesson";
const quote = 'She said "start".';
const escaped = 'Asha\'s lesson';

Both notice and escaped contain Asha's lesson. The backslash escapes an apostrophe that would otherwise close the single-quoted string.

Prefer the primitive "KG" to new String("KG"). The constructor creates an object, which affects comparisons and is rarely what a beginner wants.

JavaScript string length, indexing, slicing, and immutability

Use one string to see how positions work:

const code = "KG-JS-2026";

console.log(code.length);      // 10
console.log(code[0]);          // "K"
console.log(code.at(-1));      // "6"
console.log(code.slice(3, 5)); // "JS"
console.log(code.slice(-4));   // "2026"

Indexes start at 0, so the ten characters occupy positions 0 through 9. A negative index passed to at() counts from the end. In slice(start, end), the start is included and the end is excluded, so slice(3, 5) takes indexes 3 and 4 only.

The string "KG-JS-2026" laid out in cells indexed 0 to 9, showing slice(3, 5) is "JS" and at(-1) is "6".

Strings are immutable. A method can calculate a changed value, but it cannot edit the original string in place.

const topic = "strings";
const upper = topic.toUpperCase();

console.log(upper); // "STRINGS"
console.log(topic); // "strings"

Store the returned value when you need the transformation.

JavaScript concatenation and template literals with computed values

The + operator joins values when either operand is a string. "Java" + "Script" produces "JavaScript". With names, include the separator explicitly: first + " " + last prevents the words from running together.

Template literals make computed values easier to read:

const learner = "Asha";
const solved = 7;
const total = 10;
const percentage = solved / total * 100;
const summary = `${learner} solved ${solved} of ${total} tasks (${percentage}%).`;

console.log(summary);
// "Asha solved 7 of 10 tasks (70%)."

The calculation is 7 / 10 = 0.7, then 0.7 * 100 = 70. Backticks also preserve intentional line breaks:

const report = `Learner: Asha
Progress: 7/10`;

The rendered lines are Learner: Asha and Progress: 7/10. Backticks earn their place when you interpolate expressions or need multiline text.

JavaScript string methods for searching, cleaning, and transforming text

Start by removing whitespace from both ends:

const raw = "  JavaScript strings are useful  ";
const clean = raw.trim();

console.log(clean);        // "JavaScript strings are useful"
console.log(clean.length); // 29

The raw value still contains its surrounding spaces because trim() returned a new string. Common methods then answer different questions about clean:

Expression

Exact result

clean.includes("strings")

true

clean.startsWith("Java")

true

clean.indexOf("strings")

11

clean.slice(0, 10)

"JavaScript"

clean.replace("useful", "immutable")

"JavaScript strings are immutable"

Splitting converts a string into an array. clean.split(" ") yields ["JavaScript", "strings", "are", "useful"]. In clean.split(" ").join("-"), JavaScript first creates that four-item array, then join("-") connects the items as "JavaScript-strings-are-useful".

JavaScript strings worked example: normalise a learner and topic key

Suppose an input must become a stable key without changing the submitted text:

const rawEntry = "  Asha Jain | JavaScript Strings  ";
const cleaned = rawEntry.trim();
const divider = cleaned.indexOf("|");

const learnerKey = cleaned
  .slice(0, divider)
  .trim()
  .toLowerCase()
  .replaceAll(" ", "-");

const topicKey = cleaned
  .slice(divider + 1)
  .trim()
  .toLowerCase()
  .replaceAll(" ", "-");

const key = `${learnerKey}/${topicKey}`;
console.log(key); // "asha-jain/javascript-strings"

Work through each value. trim() gives "Asha Jain | JavaScript Strings". Counting from zero, Asha occupies indexes 0 to 3, the first space is 4, Jain is 5 to 8, the next space is 9, and | is index 10. Therefore, divider is 10.

The left slice becomes "Asha Jain ", then trimming, lowercasing, and replacing spaces gives "asha-jain". Starting at divider + 1, which is index 11, produces " JavaScript Strings"; the same steps give "javascript-strings". The template literal joins them into "asha-jain/javascript-strings", while rawEntry remains unchanged.

A pipeline that trims and lowercases "Asha Jain | JavaScript Strings" into the key "asha-jain/javascript-strings".

JavaScript string errors: diagnose the output before fixing the code

Mismatched delimiters stop parsing:

const topic = "JavaScript strings'; // SyntaxError

Fix it as const topic = "JavaScript strings";. By contrast, "Asha's lesson" is valid because the apostrophe does not close a double-quoted string.

Other mistakes run without an obvious failure:

  • new String("KG") === "KG" is false because an object is not strictly equal to a primitive.

  • After let label = " KG "; label.trim();, label is still " KG ". Assign the returned string with label = label.trim().

  • "ha ha".replace("ha", "hi") gives "hi ha", while replaceAll("ha", "hi") gives "hi hi".

Coercion creates another trap. "5" + 2 is "52" because one operand is a string, while Number("5") + 2 is 7. For slicing, "JavaScript".slice(4, 10) is "Script": index 4 is included, index 10 is excluded, and the second argument is not a character count.

JavaScript strings exercises and common assessment patterns

Run these only after predicting each result:

  1. Evaluate "JavaScript".slice(4, 10).

  2. Compute " KG AI ".trim().length.

  3. Change both occurrences of blue in "red-blue-blue" to green.

The answers are "Script", 5, and "red-green-green". The third expression is "red-blue-blue".replaceAll("blue", "green").

For a short build exercise, convert "JavaScript String Practice" to "javascript-string-practice":

const input = "JavaScript String Practice";
const output = input.toLowerCase().replaceAll(" ", "-");

Explain why input stays unchanged. String assessments commonly test output tracing, off-by-one slicing, primitive-versus-object comparison, coercion, and a small normalisation function. For placement preparation beyond language-level output tracing, TCS NQT Exam Structure, Explained Section by Section maps the assessment sections you need to prepare.

JavaScript strings: the short version and next steps

Keep six rules ready:

  1. Match the opening and closing quote.

  2. Start indexes at zero.

  3. Treat every string as immutable.

  4. Use template literals for interpolation and intentional line breaks.

  5. Remember that slice() excludes its end index.

  6. Inspect and store the value returned by each method.

The Complete JavaScript Course is the structured next step if you want the full JavaScript sequence. If you are comparing open learning paths first, use Free Courses & Guidance by Prashant Sir and choose the route that matches your present goal.