Home > Enterprise >  How to find the index of a character, searching from right to left?
How to find the index of a character, searching from right to left?

Time:10-31

Is there a JavaScript function to search for a character in a string (like string.indexOf), but search from right to left?

CodePudding user response:

This adds a function to strings.

String.prototype.indexOfRTL = function(search) {
  return (this.length - 1) - [...this].reverse().join("").indexOf(search);
}

Now using "Hello There!".indexOfRTL("e") will result in 10, for example.

CodePudding user response:

let a = 'Some guy';
let b = a.length - a.indexOf('m') - 1;
console.log(b);

  • Related