Hello i want to ask how to separate words in a sentences string without commas, when the initial letter is capitalized from the previous letter then the word is separated
example
let str = "WishYourLuck"
//expected output = Wish Your Luck
**thank you in advance
You can replace using regexp that captures word ends /([a-z])([A-Z])/g ie small letter followed by capital letter.
let str = "WishYourLuck"
console.log(str.replace(/([a-z])([A-Z])/g, (_, a, b) => `${a} ${b}`))
W/o replace
let str = "WishYourLuck"
console.log(splitWords(str))
function splitWords(str) {
const out = []
for (let i = 0; i < str.length; i++) {
const char = str[i]
const prevChar = str[i-1]
if (i && char >= 'A' && char <= 'Z' && prevChar >= 'a' && prevChar <= 'z') {
out.push(' ')
}
out.push(char)
}
return out.join('')
}
A little too late. Here is how to do it step by step.
const str = "WishYourLuck";
const arr = [...str];
let res = '';
arr.forEach((c) => {
if (c == c.toLowerCase()) {
res += c; // The character is lowercase
} else {
res += ' ' + c; // The character is uppercase
}
})
console.log(res)