Here are some of the most used String Methods all given in one big chunk of example. I always keep such examples handy for me, if in anytime I have to refer to it in case of needs.
Helpful for beginners !!!
//String methods
const airline = "Welcome to the Air India"
const plane = "A320"
console.log(plane[0]) //'A'
console.log('B373'[2]) //'7'
console.log(airline.length) //'24'
console.log(airline.indexOf('i')) //'16'
console.log(airline.lastIndexOf('i')) //'22'
console.log(airline.indexOf('to',3))//'8'
console.log(airline.slice(4))//'ome to the Air India'
console.log(airline.slice(4,7))//'ome'
console.log(airline.slice(0, airline.indexOf('to')-1)) //'welcome' without space if we remove -1 then it will be 'welcome '
console.log(airline.slice(airline.lastIndexOf(' ')+1)) //'India' if we remove +1 then ' India' . this means that slice logs first argument and logs the last argument
console.log(airline.slice(3, -3)) //'come to the Air In'
//lets see if we create a new string way
let str = new String('Airlines')
let str2 = 'plane'
console.log(str) //string 'Airlines'
console.log(typeof str) //Object
console.log(typeof str2) //string
console.log(typeof str.slice(2,5)) //string
console.log(str.toLowerCase()) //airlines
console.log(str.toUpperCase()) //AIRLINES
const captalize_plane = str2[0].toUpperCase() + str2.slice(1)
console.log(captalize_plane) //Plane
const announce ='All passenger come to door 23 stand next to the door 24'
console.log(announce.replace('door','gate')) //All passenger come to gate 23 stand next to the door 24
console.log(announce.replace(/door/i,'gate')) //All passenger come to gate 23 stand next to the door 24
console.log(announce.replace(/door/g,'gate')) //All passenger come to gate 23 stand next to the gate 24
//here " / / " is use to make the regular statement and the flag g is use to make sure it is the global object so all accurance of door in the string will be change
const myString = "Hello World";
console.log(myString.startsWith("Hello")); // true
console.log(myString.endsWith("World")); // true
console.log(myString.includes("o")); // true
console.log(myString.includes("foo")); // false
const paddedString1 = "5";
console.log(paddedString1.padStart(4, "0")); // "0005"
const paddedString2 = "10";
console.log(paddedString2.padEnd(4, "0")); // "1000"
const trimmedString = " Hello, World! ";
console.log(trimmedString.trim()); // "Hello, World!"
const repeatedString = "Hello";
console.log(repeatedString.repeat(3)); // "HelloHelloHello"
const words = ["Hello", "World", "Replit"];
const joinedString = words.join(" "); // "Hello World Replit"
Top comments (0)