String Manipulation Techniques Every Developer Should Know

String manipulation is a daily task for developers. Here are the most common operations and how to do them efficiently.

Case Conversion

JavaScript

const str = "Hello World";

// Uppercase
str.toUpperCase();  // "HELLO WORLD"

// Lowercase
str.toLowerCase();  // "hello world"

// Title Case (capitalize each word)
str.replace(/\b\w/g, char => char.toUpperCase());  // "Hello World"

// Camel Case
str.replace(/\s+(\w)/g, (_, char) => char.toUpperCase()).replace(/^\w/, c => c.toLowerCase());  // "helloWorld"

// Snake Case
str.toLowerCase().replace(/\s+/g, '_');  // "hello_world"

// Kebab Case
str.toLowerCase().replace(/\s+/g, '-');  // "hello-world"

Trim & Whitespace

const str = "  Hello World  ";

// Remove leading/trailing whitespace
str.trim();  // "Hello World"

// Remove all whitespace
str.replace(/\s+/g, '');  // "HelloWorld"

// Collapse multiple spaces
str.replace(/\s+/g, ' ').trim();  // "Hello World"

String Escaping

HTML Escaping

function escapeHtml(str) {
  return str
    .replace(/&/g, '&')
    .replace(//g, '>')
    .replace(/"/g, '"')
    .replace(/'/g, ''');
}

escapeHtml('');
// <script>alert("XSS")</script>

JavaScript String Escaping

function escapeJs(str) {
  return str
    .replace(/\\/g, '\\\\')
    .replace(/'/g, "\\'")
    .replace(/"/g, '\\"')
    .replace(/\n/g, '\\n')
    .replace(/\r/g, '\\r')
    .replace(/\t/g, '\\t');
}

Find & Replace

const str = "The quick brown fox jumps over the lazy dog";

// Replace first occurrence
str.replace('the', 'a');  // "The quick brown fox jumps over a lazy dog"

// Replace all occurrences (regex with g flag)
str.replace(/the/gi, 'a');  // "a quick brown fox jumps over a lazy dog"

// Replace with function
str.replace(/\b\w{4}\b/g, word => word.toUpperCase());
// "The QUICK brown FOX jumps OVER the LAZY dog"

✂️ Transform Strings Instantly

Use our free String Lab to convert case, escape characters, encode/decode, and perform regex find/replace operations.

Open String Lab →

Substring Operations

const str = "JavaScript";

// Extract substring
str.substring(0, 4);  // "Java"
str.slice(0, 4);  // "Java"
str.slice(-6);  // "Script" (from end)

// Split
str.split('a');  // ["J", "v", "Script"]

// Check if contains
str.includes('Script');  // true
str.startsWith('Java');  // true
str.endsWith('Script');  // true

Advanced Techniques

Slug Generation

function slugify(str) {
  return str
    .toLowerCase()
    .trim()
    .replace(/[^\w\s-]/g, '')
    .replace(/[\s_-]+/g, '-')
    .replace(/^-+|-+$/g, '');
}

slugify("Hello World! This is 2026");  // "hello-world-this-is-2026"

Truncate with Ellipsis

function truncate(str, maxLength) {
  if (str.length <= maxLength) return str;
  return str.slice(0, maxLength - 3) + '...';
}

truncate("This is a very long string", 20);  // "This is a very lo..."

← Back to Blog