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

178
Views
why id is found at position 1 in str.indexof() in js

let str = 'Widget with id';

alert( str.indexOf('Widget') ); // 0, because 'Widget' is found at the beginning

alert( str.indexOf('widget') ); // -1, not found, the search is case-sensitive

alert( str.indexOf("id") ); // 1

about 4 years ago ยท Juan Pablo Isaza
3 answers
Answer question

0

There is an "id" inside "Widget"

about 4 years ago ยท Juan Pablo Isaza Report

0

Look closer to your string: "Widget with id" ๐Ÿ˜„

The first occurrence is found after "W..." which is the index of 1.

W ๐Ÿ‘‰ 0

i ๐Ÿ‘‰ 1 โœ…

d ๐Ÿ‘‰ 2

g ๐Ÿ‘‰ 3

e ๐Ÿ‘‰ 4

t ๐Ÿ‘‰ 5

about 4 years ago ยท Juan Pablo Isaza Report

0

If you would like to find the whole word, you can use a function something like this.

  • Break the string into an array
  • iterate through the array
  • change each word into an array of chars
  • iterate through the chars array and keep a running count of each letter
  • increment your count by one after each word to account for the spaces
  • stop the iteration when the word is found

let str = 'Widget with id';

function findIndexOfWholeWord(str, searchStr){
  const words = str.split(' ')
  let numOfChars = 0
  
  for(let word of words){
   if(word === searchStr) break
    word.split('').forEach(char=>numOfChars++)
    numOfChars++
  }
  return numOfChars
}
console.log(findIndexOfWholeWord(str,'id')) //12

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!