-2

Im trying to get the position number of a certain character in a string for example I wanna get the number of the 2 in this string

var = "hello 2 world!";

Please help me to solve this Im stuck

ra fik
  • 92
  • 8
  • Possible duplicate of [How to get the positions of an specified char?](https://stackoverflow.com/questions/31780980/how-to-get-the-positions-of-an-specified-char) – GBouffard Sep 26 '19 at 21:10

2 Answers2

2
var test = 'Hello 2 world';
var pos = test.indexOf('2');
// pos === 6

The indexOf() method returns the index within the calling String object of the first occurrence of the specified value. Returns -1 if the value is not found.

see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf for more detail

Luke
  • 418
  • 4
  • 11
-1
let test = "hello 2 world";
let array = test.split('');

for (let i = 0; i < array.length; i++) {
    if (!isNaN(array[i])) {
        return i;
    }
}
Lennert Hofman
  • 585
  • 6
  • 21
  • 2
    The provided answer was flagged for review as a Low Quality Post. Here are some guidelines for [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). This provided answer may be correct, but **it could benefit from an explanation**. Code only answers are not considered "good" answers. From [review](https://stackoverflow.com/review). – MyNameIsCaleb Sep 27 '19 at 01:47