Link to home
Start Free TrialLog in
Avatar of juan field
juan field

asked on

(Javascript) can i get the indexOf from a string without using the indexOf method ?

Given a character and a string, "getIndexOf" returns the first position of the given character in the given string.

Notes:
* Strings are zero indexed, meaning the first character in a string is at position 0.
* When a string contains more than one occurrence of a character, it should return the index of its first occurrence.
* If the character does not exist in the string, it should return -1.
* Do not use the native indexOf function in your implementation.

var output = getIndexOf('a', 'I am a hacker');
console.log(output); // --> 2

Starter Code :
function getIndexOf(char, str) {
  // your code here
}
ASKER CERTIFIED SOLUTION
Avatar of Shaun Vermaak
Shaun Vermaak
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of juan field
juan field

ASKER

thank you so much this really helped me. Happy new year.
Anytime, happy new year to you too
This looks like an assignment in which case you should first try to solve the problem yourself and then post what you have done here. It is not good getting someone else to do it for you as you do not learn from the experience.

In JavaScript strings are arrays of characters. Consider this code

var str = 'I am a hacker';
for(var i = 0; i < str.length; i++) {
   console.log(str[i]);
}

Open in new window


Run that and view in the console - what do you see?

Now to compare characters how do you go about doing that. In your starter function you were given

function getIndexOf(char, str) {

Open in new window


char is the character you are comparing right? And in the above code (loop) we are outputting a character from the array using ....?

All that is required is to check if those two are equal and to return ... what - what is keeping track of where we are in the loop?

If there is a match then we exit the function from the loop - no problem - but what if there is no match - we need some default action at the end to return the -1 if no char was found.

Using the above see if you can improve on the answer above by coding it yourself.
You do not learn anything unless you try yourself...
thank so much for your feedback . I am new to the industry and to the page. Happy new year.