Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

138
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!