Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

72
Vistas
JavaScript: Search string from position

JavaScript has two useful methods, both which nearly do what I need.

  • String.prototype.indexOf() will search for a substring and return its position. It has an optional position parameter which is the starting point of the search, so you can easily find the next one.
  • String.prototype.search() will search a string using a regular expression and return its position. However, as far as I can tell, it doesn’t allow a starting position, so it always searches from the start.

Is there anything which allows me to find the position using a regular expression which does allow for a starting position?

about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

You could do a String#slice in advance to get rid of unwanted parts and then take String#search.

function search(string, regexp, from = 0) {
    const index = string.slice(from).search(regexp);
    return index === -1
        ? -1
        : index + from;
}
about 4 years ago · Santiago Trujillo Denunciar

0

In order to get the position of the original position of the search result you could use Nina Scholz' approach and then re-add the characters removed from the start. For Instance:

const str = "Hello World!";
let start = 5;
const output = str.substring(start).search(/World/g) + start;
console.log(output); //6

Note: Be careful with cases where .search() returns -1.

about 4 years ago · Santiago Trujillo Denunciar

0

The other answer is the way to go as its much clearer what the intention is, but if you had to use a regular expression, you could do it like this:

// This string should not include characters that have special
// meaning in regular expressions / should be escaped.
const inputString = "foo bar baz bar";
const offset = 8;
const searchString = "bar";
inputString.search(new RegExp(`(?=.{${offset}}${searchString}`));

//  (?=             make sure ${searchString} ("bar") 
//                  is preceded by:
//  .               anything
//  {$(a number)}   at least this many times:
//                  {8} in this example.

// The (?=A)B positive lookahead won't be included in the result,
// so you don't need to plus or minus the offset from the result:

// Example:
const str = 'aabbcc aabbcc aabbcc';
               ^      ^      ^
               2      9      16

str.search(new RegExp(`(?<=.{${0}})bb`));
// Return 2

str.search(new RegExp(`(?<=.{${4}})bb`));
// Returns 9

str.search(new RegExp(`(?<=.{${10}})bb`));
// Returns 16

str.search(new RegExp(`(?<=.{${1000}})bb`));
// Returns -1

str.search(new RegExp(`(?<=.{${10}})doesntexist`));
// Returns -1
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda