In Javascript, we can access string character by referring to it’s index number, a method similar to extracting array elements from an array.
let arr1 = ["c","o","d","i","n","g"]; let arr2 = arr1[0]; console.log(arr2); // c let str1 = "coding"; let str2 = str1[0]; console.log(str2) // c
How To Use Array Methods On Strings In Javascript?
Since strings can behave like an array, we can manipulate strings with array methods.
let str = "coding" let str2 = Array.prototype.map.call(str, function(x) { return x.toUpperCase(); }) console.log(str2); // [ 'C', 'O', 'D', 'I', 'N', 'G' ] let str1 = "coding"; Array.prototype.forEach.call(str1, function(str, index) { console.log(str, index) }); // c 0 // o 1 // d 2 // i 3 // n 4 //g 5 let str1 = "coding"; let str2 = Array.prototype.findIndex.call(str1, function(x){ return x == "o"; }); console.log(str2); // 2
Remember strings are primitive values and immutable. It can not be altered so use of array methods such as push, pop, shift, unshift,splice and splice will fail.