Add Space In Middle Of String Javascript

3 min read Jun 22, 2024
Add Space In Middle Of String Javascript

Adding Space in the Middle of a String in JavaScript

Adding a space in the middle of a string in JavaScript can be accomplished in a few different ways. Here's a breakdown of common methods:

1. Using String Concatenation

This method involves splitting the string at the desired point, adding a space, and then concatenating the resulting parts.

function addSpace(str, position) {
  return str.substring(0, position) + " " + str.substring(position);
}

let myString = "HelloWorld";
let spacedString = addSpace(myString, 5);
console.log(spacedString); // Output: "Hello World"

2. Using String Interpolation

String interpolation provides a cleaner way to insert a space within a string.

function addSpace(str, position) {
  return `${str.substring(0, position)} ${str.substring(position)}`;
}

let myString = "HelloWorld";
let spacedString = addSpace(myString, 5);
console.log(spacedString); // Output: "Hello World"

3. Using the slice() Method

The slice() method allows you to extract a portion of the string.

function addSpace(str, position) {
  return str.slice(0, position) + " " + str.slice(position);
}

let myString = "HelloWorld";
let spacedString = addSpace(myString, 5);
console.log(spacedString); // Output: "Hello World"

4. Using the substr() Method

The substr() method extracts a substring from a given starting position and length.

function addSpace(str, position) {
  return str.substr(0, position) + " " + str.substr(position);
}

let myString = "HelloWorld";
let spacedString = addSpace(myString, 5);
console.log(spacedString); // Output: "Hello World"

5. Using Regular Expressions

Regular expressions can be used to insert a space at a specific character position.

function addSpace(str, position) {
  return str.replace(new RegExp(`^.{${position}}`), match => `${match} `);
}

let myString = "HelloWorld";
let spacedString = addSpace(myString, 5);
console.log(spacedString); // Output: "Hello World"

Remember to choose the method that best suits your needs and coding style.

Latest Posts