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]);
}
CodePudding user response:
You can use substring to take parts of your input:
let name = "mynameisprogrammer";
for (let index = 1; index <= name.length; index ) {
let finalData = name.substring(0, index);
console.log(finalData);
}
CodePudding user response:
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; }
CodePudding user response:
You can simply use a variable and keeping add value of current index and keep printing on each iteration, you don't need split here
let name = "helloguys";
function printName(name) {
let temp = ''
for (let index = 0; index < name.length; index ) {
temp = name[index]
console.log(temp);
}
}
printName(name)
CodePudding user response:
This is how you could do it.
I'm not sure if you wanted them to be object otherwise you could use string.substring
let name = "mynameisprogrammer";
for (let index = 0; index < name.length; index ) {
let finalData = name.split("");
console.log(finalData.slice(0,index 1).join(""));
}
CodePudding user response:
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