String.prototype.indexesOf()

Would work like

String.prototype.indexesOf = function(char) {
    return [...this.matchAll(new RegExp(char, 'gi'))].map(a => a.index) // Returns array of indexes
}

It's easy enough to do yourself. Would like to see this added.

That particularly implementation would fail on any char that required escaping in a regex. What you want is something a bit different.

Either way tho, what's the use case? Why would you need all the matching indexes?

1 Like

e.g. remove all of character x of a string would be like

let str = 'banana'

// remove every n
let ns = string.indexesOf('n');
for (var i = 0; i < ns.length; i++) {
    str = str.substring(0, ns[i] - 1) + str.substring(ns[i], str.length);
}

console.log(str); // <-- baaa

or str.replaceAll('n', '')?

1 Like

You could iterate through all indices using

for (var i = -1; (i = string.indexOf('n', i + 1)) !== -1;) {
   // ...
}
1 Like