-1

This topic has been widely asked and discussed and yet I still cannot find a solution for my particular problem.

I need to create a function that returns the index for the first occurrence of a character in a string..seems simple enough, however I cannot use any built in functions such as; indexof,lastIndexOf,search,startsWith,findIndex, essentially anything that would make this easier and stop me from asking a question that has so clearly already been answered.

So far what I have is something like this:

function searchIndex(str,index){
let x = str.charAt(index);
console.log(x);
}

I understand that charAt requires an index, now my question is is there anyway I can make this work? My thinking when writing this was, if I throw in a string such as 'abc' and give an index of 0, it would return 'a', however I get an error that says charAt is not a function. Which tells me my thinking was incorrect and that I cant just use index parameter from the function as an index for charAt.

Any help or direction to solve this problem would be greatly appreciated.

edited charAT to charAt, apologies.

4
  • 1
    It's charAt not charAT Commented Mar 13, 2019 at 1:59
  • You'll want to iterate through the string. You can access str.length to return the length of the string, and you can access individual characters like str[i]. See stackoverflow.com/questions/1966476/… Commented Mar 13, 2019 at 2:01
  • Are you using built in function then your syntax is for the function is wrong i.e. it should be charAt (index) not charAT (index).But if you are using custom function then please show your code. Commented Mar 13, 2019 at 2:06
  • 2
    str.indexOf(char) should works. ``` var str = 'abcabc'; str.indexOf('a'); // => 0 ``` Commented Mar 13, 2019 at 2:07

6 Answers 6

2

Is this close to what you're looking for?

function findCharIndex(str,char){
  for (let index = 0; index < str.length; index++) {
     if (str[index] === char) {
       return index;
     }        
  }
  return -1;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Iterate through each element in str and check if it's the character you want:

let string = "This is a string";
let char = "a";
let index;
for (let i = 0; i < string.length; i++) {
  if (string[i] == char) {
    index = i;
    break;
  }
}

console.log(index);

2 Comments

Done @MiroslavGlamuzina
0

Another way to do it, assuming you can use Array.entries()

const str = "This is a string";
const char = "a";

function findCharIndex(str, char) {
  for (let [index, val] of [...str].entries()) {
    if (val === char) {
      return index;
    }
  }
}

console.log(findCharIndex(str, char));

Comments

0

This should suit your needs:

findFirstOccurance = (str, char) => Array.from(str).findIndex(c => c === char)

let str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.";

console.log(findFirstOccurance(str, 'a'));

If it has to be deconstructed even further, do:

findFirstOccurance = (str, char) => {
  for (let i = 0; i < str.length; i++) {
    if (str[i] === char) {
      return i;
    }
  }
  return -1; // or false, whichever you prefer.
}

let str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis ute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.";

console.log(findFirstOccurance(str, 'a'));

Hope this helps,

Comments

0

Alternative: use a while loop

function searchIndex(string, character2Find, zeroBased = true) {
  let i = 0;
  do { i+=1; } while (i < string.length && string[i] !== character2Find);
  
  return i >= string.length ? -1 : i + +!!!zeroBased;
}

console.log(`first l in "hello world" at (starts from 0): ${
  searchIndex(`hello world`, `l`)}`);
console.log(`first x in "hello world" at (starts from 0): ${
  searchIndex(`hello world`, `x`)}`);
console.log(`first r in "hello world" at (starts from 0): ${
  searchIndex(`hello world`, `r`)}`);
console.log(`first l in "hello world" at (starts from 1): ${
  searchIndex(`hello world`, `l`, false)}`);
console.log(`first x in "hello world" at (starts from 1): ${
  searchIndex(`hello world`, `x`, false)}`);
console.log(`first r in "hello world" at (starts from 1): ${
  searchIndex(`hello world`, `r`, false)}`);

Or use matchAll:

function searchIndex(string, char2Find, zeroBased = true) {
  const index = [...string.matchAll(RegExp(char2Find, `g`))]?.[0]?.index;
  return  index ?  index + +!!!zeroBased : -1;
}

console.log(`first l in "hello world" at (starts from 0): ${
  searchIndex(`hello world`, `l`)}`);
console.log(`first x in "hello world" at (starts from 0): ${
  searchIndex(`hello world`, `x`)}`);
console.log(`first r in "hello world" at (starts from 0): ${
  searchIndex(`hello world`, `r`)}`);
console.log(`first l in "hello world" at (starts from 1): ${
  searchIndex(`hello world`, `l`, false)}`);
console.log(`first x in "hello world" at (starts from 1): ${
  searchIndex(`hello world`, `x`, false)}`);
console.log(`first r in "hello world" at (starts from 1): ${
  searchIndex(`hello world`, `r`, false)}`);

Comments

-2

The match method can be used in JavaScript.

function findCharIndex() {
    haystack = "this is a string" 
    needle = "a" // "is","string"
    let matchWord = haystack.match(needle);
    if(!matchWord){
        return -1;
    }
    return matchWord.index;
};

console.log(findCharIndex());

Or

function findCharIndex() {
    let haystack = "this is a string";
    let needle = "a"; // or "is", "string"
    let index = haystack.indexOf(needle);
    return index !== -1 ? index : -1;
}

console.log(findCharIndex());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.