Javascript String indexOf() find all location of substrings

Introduction

The following code shows how to locate all instances of a substring by looping callings to indexOf():

let stringValue = "Lorem ipsum dolor sit amet, consectetur adipisicing elit";
let positions = new Array();
let pos = stringValue.indexOf("e");

while (pos > -1) {
    positions.push(pos);//from  www  .j  a  v  a  2  s .  c  om
    pos = stringValue.indexOf("e", pos + 1);
}

console.log(positions);

This example works through a string by increasing the position at which indexOf() should begin.




PreviousNext

Related