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

140
Vistas
find specific word in a string function is acting... odd (javascript)

Alright, so I have this function that is suppose to log a specific word it finds in a string into the console. But it kinda... yeah it don't work.

function foo(input) {
  for (var i = 0; i < input.length; i++) {
    const character = input[i]
    // To make sure it doesnt always get 
    // the very first blank space I do the following \/ (I think this is the trouble area)
    const word = input.substring(i, input.substring(i, input.length).indexOf(' '))
    console.log(word)
    if (word == "foo bar") {
      console.log(word)
      console.log("worked!") // <- currently does not fire
      // word should only print "foo bar" without linebreaks
    }
  }
}
foo("  foo bar  ");

I don't even know how to explain what is happening. But I am sure this scary image will give you an idea.

web browser console

the expected output, with some line breaks above or below, is:
"f"
"fo"
"foo"
"foo "
"foo b"
"foo ba"
"foo bar"
"worked!"

ALSO keep it mind that this does not work with or without line breaks (I testing both) and I would like it to work with both.

examples:

// single line (does not work)
foo("  foo bar   ")

// line breaks (does not work)
foo(`
    foo bar
`)


about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Define word out of the for loop... And add the current character to it at each iteration.

const input = "foo bar"

function foo(input) {
  let word = ""  // Define it out of the loop
  for (var i = 0; i < input.length; i++) {
    const character = input[i]
    word += character  // add the current loop character here
    
    console.log(word)
    
    if (word == "foo bar") {
      console.log("worked!") // <- is firing now
    }
  }
}

foo(input)

From comment:

if I have the string "This is a foo bar lalalalala" I want to get just the "foo bar" part.

Then using match would be the way.

const input = "This is a foo bar lalalalala"

function foo(input) {
  let match = input.match(/foo bar/)

  if (match) {
    console.log("worked!") // <- is firing now
  }
}

foo(input)

about 4 years ago · Juan Pablo Isaza 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