0

I can check that a string includes letter with using of .indexOf():

my_string = 'sdf sdfdsf dfdsdfs';
console.log(my_string.indexOf(' '));
// returns 4

Is exists method to do the same but from end to begin? (example above must returns 11 - the first white space from right to left)

AlexAstanin
  • 343
  • 1
  • 4
  • 14
  • @James Nope, different questions. – Scimonster Oct 27 '14 at 12:39
  • 1
    `console.log(my_string.indexOf(' '));` returns 3 with your input, not 4. I don't know how you're expecting "11"; the first white space from right to left is in the 9th position? – Matt Oct 27 '14 at 12:43
  • @user3775292, First white space from right to left is the 11th position from l to r and is index 10 from l to r – The One and Only ChemistryBlob Oct 27 '14 at 12:45
  • If you're expecting 11 (actually, 10) then you're counting from left to right, not right to left as you state. Therefore the answers featuring `lastIndexOf()` will work for you. If you *don't* mean that, then @Savv's answer will work. – Ben Oct 27 '14 at 12:45

3 Answers3

2

Reverse your string and perform indexOf():

reverseString = my_string.split("").reverse().join("");
console.log(my_string.length - reverseString.indexOf(' '));
Savv
  • 433
  • 2
  • 7
2

Use lastIndexOf.

my_string = 'sdf sdfdsf dfdsdfs';
console.log(my_string.lastIndexOf(' '));
Scimonster
  • 32,893
  • 9
  • 77
  • 89
0

You can try this

console.log(my_string.lastIndexOf(" "));
sp_m
  • 2,647
  • 8
  • 38
  • 62