Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Substring Function in JS

Hello everyone! How would I create my own substring function for a challenge? I came off on this challenge asking me to create my own substring! I've researched and tried on my own but haven't figured it out? Can anyone please help me! Thank You

Steven Parker
Steven Parker
220,378 Points

I'm not quite clear on what the objective is. Can you provide a link to the page you are referring to?

The objective is how do you create YOUR OWN substring function

Steven Parker
Steven Parker
220,378 Points

Sure, but I'm not clear on what a "substring function" would do. I'm expecting the page you saw this on would be likely to provide those details. Can you post a link to it here?

1 Answer

Steven Parker
Steven Parker
220,378 Points

Without seeing the actual instructions, I'm going to guess that what you want to do is to re-create the functionality of the built-in "substr" string method. So, start with the functional definition (obtained from MDN):

str.substr(start[, length]) extracts length characters from a string, counting from the start index.

You might begin with a loop that goes from the "start" value and runs for "length" characters, or until the end, whichever is shorter.

Inside your loop, you might take the character from the current index position and add it to a new string being created.

When the loop ends you could return the newly-created string.

So if I have the right idea, that should help you get started.

can you please give me an example of what you just explained

Steven Parker
Steven Parker
220,378 Points

There are plenty examples of loops, indexing, and using string properties throughout the courses. I'm only suggesting a way to combine them to create a specific functionality like the "substr" method.