I'm trying to split my string but not get proper output as per my expected.
Input
let name = "helloguys";
Output
h
he
hel
hell
hello
hellog
hellogu
helloguy
helloguys
let name = "mynameisprogrammer";
for (let index = 1; index <= name.length; index++) {
let finalData = name.split(name[index]);
console.log(finalData[0]);
}
You could use Array.map() along with String.slice() to split the string into the required values:
let name = "mynameisprogrammer";
let result = [...name].map((chr, idx) => name.slice(0, idx + 1));
console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; }
If you need this to be unicode aware, you might want to avoid using string substring / slice etc.
Instead convert to array, and split there.
eg..
let name = "my😀name🤣is🫠programmer👍";
const nameA = [...name];
for (let ix = 1; ix <= nameA.length; ix += 1)
console.log(nameA.slice(0, ix).join(''));
.as-console-wrapper { max-height: 100% !important; }
ps. To see what I mean by unicode aware, try using the name from the code above into some of the other answers.