javascript string index code example

Example 1: how to get the first character of a string in javascript

let str = 'John Wick'
let firstChar = str.charAt(0) 
console.log(firstChar); // "J"

Example 2: javascript indexof

//indexOf getting index of array element, returns -1 if not found
var colors=["red","green","blue"];
var pos=colors.indexOf("blue");//2

//indexOf getting index of sub string, returns -1 if not found
var str = "We got a poop cleanup on isle 4.";
var strPos = str.indexOf("poop");//9

Example 3: indexof javascript

//indexOf - JS method to get index of array element. 
// Returns -1 if not found

var colors=["red","green","blue"];
var pos=colors.indexOf("blue");//2

//indexOf getting index of sub string, returns -1 if not found

var str = "We got a poop cleanup on isle 4.";
var strPos = str.indexOf("poop");//9

//Eg with material ui

<Checkbox
   checked={value.indexOf(option) > -1}
   value={option}
/>

Example 4: indefOf

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));
// expected output: 1

Example 5: js indexof string

str.indexOf(searchValue[, fromIndex])

Example 6: indexof javascript

Array.indexOf(searchElement, fromIndex)