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 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); }
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 = "mynameisprogrammer"; 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.
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)
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("")); }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.