Return first capital letter and its index


Posted by Christy on 2022-04-19

Description: Write a function named position that accepts a string and returns the first letter of this string and its index number, if there’s no capital letter then return -1

function position(str) {

}

console.log(position("abcd")); // -1
console.log(position("AbcD")); // A 0
console.log(position("abCD")); // C 2

First I will find how to get first letter and its index

function position(str) {
  for (let i = 0; i < str.length; i++) {
    return str[i] + " " + i;
  }
}

Answer:

function position(str) {
  for (let i = 0; i < str.length; i++) {
    if (str[i] >= "A" && str[i] <= "Z") {
      return str[i] + " " + i;
    }
  }
  return -1;
}

Reflection:

  1. The key is to search the string of every index to check if there’s capital letter or not, if not then return -1.

    Be careful to check the condition return -1 should be executed after searching every index of the string

  2. If return switch to console.log(), it will show all capital letter and its index and finally return -1

return and console.log() are two different stories.

function position(str) {
  for (let i = 0; i < str.length; i++) {
    if (str[i] >= "A" && str[i] <= "Z") {
      console.log(str[i] + " " + i);
    }
  }
  return -1;
}

console.log(position("AbcD")); 
// A 0
// D 3
// -1

Another answer 1:

function position(str) {
  for (let i = 0; i < str.length; i++) {
    if (str[i] === str[i].toUpperCase()) {
      return str[i] + " " + i;
    }
  }
  return -1;
}

console.log(position("abcd")); // -1
console.log(position("aBCd")); // B 1

Another answer 2:

function position(str) {
  let i = 0;
  do {
    if (str[i] >= "A" && str[i] <= "Z") {
      return str[i] + " " + i;
    }
    i++;
  } while (i < str.length);
}

Another answer 3:

function position(str) {
  let i = 0;
  while (i < str.length) {
    if (str[i] >= "A" && str[i] <= "Z") {
      return str[i] + " " + i;
    }
    i++;
  }
  return -1;
}









Related Posts

JavaScript ES6

JavaScript ES6

PHP CodeIgniter 資料庫字詞替換

PHP CodeIgniter 資料庫字詞替換

《Designing Web APIs》ch2 API Paradigms

《Designing Web APIs》ch2 API Paradigms


Comments