Home > other >  find specific word in a string function is acting... odd (javascript)
find specific word in a string function is acting... odd (javascript)

Time:04-21

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
`)


CodePudding user response:

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)

  • Related