JAVASCRIPT

Normalize Whitespace: Replace Multiple Spaces and Trim with Regex

Efficiently clean up text by replacing multiple consecutive spaces with a single space and trimming leading/trailing whitespace using regex in JavaScript.

function normalizeWhitespace(text) {
  // Replace multiple spaces with a single space, then trim leading/trailing whitespace
  return text.replace(/\s+/g, ' ').trim();
}

// Examples:
// console.log(normalizeWhitespace("  Hello   World!   ")); // "Hello World!"
// console.log(normalizeWhitespace("No extra spaces.")); // "No extra spaces."
// console.log(normalizeWhitespace("   Only leading/trailing.   ")); // "Only leading/trailing."
How it works: This JavaScript snippet provides a `normalizeWhitespace` function that cleans up a string. It first uses the regex `/\s+/g` to find all occurrences of one or more whitespace characters and replaces them with a single space. Afterward, the `.trim()` method removes any leading or trailing whitespace, resulting in a clean, normalized string.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs