Ahmed
Ahmed

Reputation: 25

Add spaces before Capital Letters then turn them to lowercase string

I'm trying to make a function that caps space in which it takes input like "iLikeSwimming" then it outputs "i like swimming".

This is my try:

function isUpper(str) {
    return !/[a-z]/.test(str) && /[A-Z]/.test(str);
}

function capSpace(txt) {
  var arr = Array.from(txt);
  for (let i = 1; i < txt.length; i++){
    if (isUpper(txt[i]) == true) {
        arr.splice((i),0,' ')
    }
  }
  return arr.join('').toString().toLowerCase();
}

It's good for strings with only one capital letter, however, it gets kind of weird with more than one.

Example Input and outputs: Inputs: capSpace("iLikeSwimming"); capSpace("helloWorld"); Outputs: 'i lik eswimming' 'hello world'

I'd really appreciate it if someone can point the issue with my code. I know there are other questions "similar" to this, but I'm trying to learn my mistake rather than just copying, I couldn't make sense of any of the other questions. Thank you!

Upvotes: 2

Views: 2123

Answers (3)

DecPK
DecPK

Reputation: 25408

1) You can simply achieve this using regex and string replace method

const capSpace = (str) => str.replace(/([A-Z])/g, (match) => ` ${match.toLowerCase()}`);

console.log(capSpace("iLikeSwimming"));
console.log(capSpace("helloWorld"));

2) You can also do with split, map and join

const capSpace = (str) =>
  str
  .split("")
  .map((s) => (/[A-Z]/.test(s) ? ` ${s.toLowerCase()}` : s))
  .join("");

console.log(capSpace("iLikeSwimming"));
console.log(capSpace("helloWorld"));

Upvotes: 5

testing_22
testing_22

Reputation: 2585

The reason why it gets weird with strings that have more than 1 capital letter is that every time you find one, you add a blank space which makes the following indices increase in a single unit.

It's a simple workaround: just place a counter splitCount to keep track of how many spaces you've added and sum it with the index i to correct the indices.

function isUpper(str) {
    return !/[a-z]/.test(str) && /[A-Z]/.test(str);
}

function capSpace(txt) {
  var arr = Array.from(txt);
  var splitCount = 0; // added a counter
  for (let i = 1; i < txt.length; i++){
    if (isUpper(txt[i]) === true) {
        // sum it with i
        arr.splice((i + splitCount),0,' ')
        splitCount++; // increase every time you split
    }
  }
  return arr.join('').toString().toLowerCase();
}
console.log(capSpace('iLikeSwimming'))

Upvotes: 5

Invizi
Invizi

Reputation: 1298

Here's a simple one I made. Matches capital letters then replaces them.

const testString = "ILoveMoney";

function caps2Spaces(str) {
  const matches = str.match(/[A-Z]/g);
  for (const letter of matches) {
    str = str.replace(letter, ` ${letter.toLowerCase()}`)
  }
  return str.trim();
}
console.log(caps2Spaces(testString));

Upvotes: 3

Related Questions