JavaScript String Methods

JavaScript String Methods

In this article I am going to give a basic foundation of JavaScript string Methods

  1. indexOf()

It returns the index within the string of first occurrence of the specified value

It returns -1 if it is not found

const str = "Hello World"
const output = str.indexOf("World")
console.log(output) // 6

Note : Indexes in JavaScript strings start at 0, not 1.

  1. replace()

    Return a new string with replace the matched substring with the new substring

     const str = "Hello World"
     const output = str.replace("World" , "India")
     console.log(output) // Hello India
    
  2. slice()

    It return a new string by extracting the part of given string. This method take two argument start index(inclusive) and end index(exclusive). In case when the end index is not given it will extend it to the end of string

     const str = "Hello World"
     const output = str.slice(6,9)
     console.log(output) // Wor
    
     const newStr = "Hello Readers"
     const newOutput= newStr.slice(7)
     console.log(newOutput) // eaders
    
    1. split()

      It return a new array after splitting the string based on the given parameter. There are two parameter separator and limit(optional)

      Separator : The pattern which determine where to split the string

       // spliting the string without any parameter
        const str = "Hello";
       const parts = str.split();
      
       console.log(parts); // Output: ["H", "e", "l", "l", "o"]
      
       // when we want to split the sting based on ","
       const str = "apple,banana,grape,orange";
       const separator = ",";
       const parts = str.split(separator);
       console.log(parts); //Output:[ 'apple', 'banana', 'grape', 'orange' ]
      
       // split a string based on the single space character
       const str = "Hello world! This is a test";
       const separator = " "; 
       const parts = str.split(separator);
       console.log(parts); 
       // Output: ["Hello", "world!", "This", "is", "a", "test"]
      
      1. startsWith()

        It return true if the string is start with the given string, othewise it return false

         const str = "Hello World";
         const startsWithHello = str.startsWith("Hello");
        
         console.log(startsWithHello); // Output: true
        
        1. toLowerCase()

          It return a new string with all the character converted to lowercase.

           const str = "Hello World"
           console.log(str.toLowerCase()) // hello world
          
          1. toUpperCase()

            It return a new string with all the character converted to Uppercase.

             const str = "Hello World"
             console.log(str.toUpperCase()) // HELLO WORLD
            

Did you find this article valuable?

Support Shivam's Blog❤️❤️ by becoming a sponsor. Any amount is appreciated!