最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Alternative to the lastIndexOf() function - Stack Overflow

programmeradmin0浏览0评论

Here is the task at hand:

"Write a function called stringLastIndexOf, which accepts two strings: the first is a word and the second is a single character.

The function should return the last index at which the character exists or -1 if the character is not found.

Do not use the built in String.lastIndexOf() function!"

I specifically am struggling with the end requirement, which is to get my function to return the exact position of where the str2 character exists. What could I do to work around not using the lastindexof function to do this?

function stringLastIndexOf(str1, str2) {
  var pos = str1.includes(str2, -1);
  if (pos !== true) {
    return -1;
  } else {
    return str2.position();
  }
}
console.log(
  stringLastIndexOf('word', 'w'),
  stringLastIndexOf('pumped', 'f')
  );
  

Here is the task at hand:

"Write a function called stringLastIndexOf, which accepts two strings: the first is a word and the second is a single character.

The function should return the last index at which the character exists or -1 if the character is not found.

Do not use the built in String.lastIndexOf() function!"

I specifically am struggling with the end requirement, which is to get my function to return the exact position of where the str2 character exists. What could I do to work around not using the lastindexof function to do this?

function stringLastIndexOf(str1, str2) {
  var pos = str1.includes(str2, -1);
  if (pos !== true) {
    return -1;
  } else {
    return str2.position();
  }
}
console.log(
  stringLastIndexOf('word', 'w'),
  stringLastIndexOf('pumped', 'f')
  );
  

Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Dec 28, 2019 at 12:47 user5617839user5617839 3
  • 3 loop through the string starting from the back. if you find a match, return whatever index you are at. return -1 outside of the for loop – Jhecht Commented Dec 28, 2019 at 12:49
  • Confused, am i allowed to use String.prototype.lastIndexOf? String.lastIndexOf doesn't even exist. – ASDFGerte Commented Dec 28, 2019 at 12:53
  • Also, since you are limited to one character in your search: const stringLastIndexOf = (str, c) => Array.prototype.lastIndexOf.call(str, c); – ASDFGerte Commented Dec 28, 2019 at 13:24
Add a ment  | 

5 Answers 5

Reset to default 4

You can loop backward:

const aLastIndexOf = (str, ch) => {
    for (let index = str.length - 1; index >= 0; index--) {
        if (str[index] == ch)
            return index;
    }
    return -1;
}

An example:

const aLastIndexOf = (str, ch) => {
    for (let index = str.length - 1; index >= 0; index--) {
        if (str[index] == ch)
            return index;
    }
    return -1;
}

console.log(aLastIndexOf("hello", 'h'));
console.log(aLastIndexOf("hello", 'l'));
console.log(aLastIndexOf("hello", 'e'));

a simple for loop can solve your problem

function stringLastIndexOf(str1, str2) {
  let index = -1
  for (var i = 0; i < str1.length; i++) {
    if (str1[i] === str2) {
      index = i
    }
  }
  return index
}
console.log(
  stringLastIndexOf('word', 'w'),
  stringLastIndexOf('pumped', 'f')
);

If you reverse the string first, you can simply use indexOf:

function stringLastIndexOf(str, c) {
  let pos = str.split("").reverse().join("").indexOf(c);
  return pos == -1 ? -1 : str.length - pos;
}

Note that the string is reversed by turning it into an array of characters using split, reversing that array, and joining the array into a string again using join.

The result of indexOf will have to be subtracted from the length of the original string.

We can reverse the string and use indexOf also we can keep edge case that passed sting can be empty like this -:

function lastIndexOf(str, char){
    return (str.length && (str.length - str.split("").reverse().indexOf(char)-1))
}

This is how I see it, betting on ES6, readability and simplicity:

const stringLastIndexOf = (str, letter) => {
    let result = -1;
    const strSplitted = str.split('');
    strSplitted.forEach((strLetter, index) => {
        if (strLetter === letter) result = index;
    });
    return result;
};

const test = stringLastIndexOf('test', 't');
console.log(test); // 3

you can try it on your browser's console and play with it

More about arrow functions, let & const, Array.prototype.split(), Array.prototype.forEach().

发布评论

评论列表(0)

  1. 暂无评论