Javascript Strings and its methods

Javascript Strings and its methods

Strings in Javascript

String declaration: In JavaScript, strings can be declared and initialized using single quotes (''), double quotes (""), or backticks (``). Here are the ways to declare strings:

const name= "John"; //String declaration using double quotes
const hobby = 'playing football'; //String declaration using single quotes
const favouriteTeam = `Barcelona` //String declaration using template literals

String methods

  1. String.concat(): String.concat method combines two strings as shown below. We can also achieve this by "+" operator. This doesn't affect the original string so if we want the result we can store it in a separate variable

     let str1 = "Hello"
     let str2 = ",There" 
     console.log(str1+str2);//Output: Hello,There
     console.log( str1.concat(str2));//Output: Hello,There
     console.log( str1);//Output: Hello
    
  2. String.toUpperCase(): As the name suggests the String.upperCase converts the string to uppercase. This doesn't affect the original string so if we want the result we can store it in a separate variable

     let str1 = "Hello"
     console.log( str1.toUpperCase());//Output: HELLO
     console.log( str1);//Output: Hello
    
  3. String.toLowerCase(): As the name suggests the String.upperCase converts the string to uppercase. This doesn't affect the original string so if we want the result we can store it in a separate variable

     let str1 = "HeLlO"
     console.log( str1.toUpperCase());//Output: hello
     console.log( str1);//Output: HeLlO
    
  4. String.charAt(): The String.charAt method returns the character present at the given index

     let city = "Liverpool"
     console.log( city.charAt(6));//Output: o
    
  5. String.indexOf(): The indexOf method returns the first index of the provided character from the string. If the provided character is not present in the string it returns -1.

     let city = "Liverpool"
     console.log( city.indexOf('v'));//Output: 2
    
     let city = "Mumbai"
     console.log( city.indexOf('C'));//Output: 2
    
  6. String.subString(): The substring() method in JavaScript retrieves a section of a string based on the provided startIndex and endIndex parameters. When both parameters are used, the resulting substring begins at the startIndex and ends just before the character at endIndex, effectively extracting characters within that range. If only the startIndex is specified, the returned substring extends from that startIndex to the end of the original string." This method doesn't affect the original string so if we want the result we can store it in a separate variable

     let city = "Mumbai"
     console.log(city.substring(1,4)) //Output: 2, 1 inclusive 4 exclusive 
     console.log(city) //Output: Mumbai
    
     let state = "Maharashtra"
     console.log(state.substring(4)) //Output: rashtra
    
  7. String.slice(): Just like the substring method the slice() method in JavaScript also retrieves a section of a string based on the provided startIndex and endIndex parameters. When both parameters are used, the resulting substring begins at the startIndex and ends just before the character at endIndex, effectively extracting characters within that range. If only the startIndex is specified, the returned substring extends from that startIndex to the end of the original string." This method doesn't affect the original string so if we want the result we can store it in a separate variable. Unlike the substring method the slice method also accepts the negative values

     let city = "Mumbai"
     console.log(city.slice(1,4)) //Output: umb, 1 inclusive 4 exclusive 
     console.log(city) //Output: Mumbai
    
     let state = "Maharashtra"
     console.log(state.slice(4)) //Output: rashtra
     console.log(state.slice(-4)) //Output: htra
    
     console.log(state.slice(-4,-1)) //Output: htr
    
  8. String.trim(): The trim method removes extra spaces from the start and end of a string. We also have the trimStart and trimEnd methods which removes the extra space from the start of the string and from the end of the string respectively.

     const newString1 = "     Hello    ";
     console.log(newString1)
     console.log(newString1.trim())  //Output: 'Hello'
     console.log(newString1.trimStart()) // 'Hello   '
     console.log(newString1.trimEnd()) // '   Hello'
    
  9. String.replace(): The replace method accepts 2 arguments first is searchValue and second is newValue. This will replace all the occurrences of the content from string then you have to use the replace method as shown below

     string.replace(searchValue, newValue)
    
     const url= "https://google.com/best%20footbal%20team"
     const url1=url.replace('%20','-');
     console.log(url1);
     const url2 = url1.replace('%20','-')
     console.log(url2)
    
  10. String.split(): Split method splits a string into an array of substrings based on a specified separator and returns the resulting array. This method is particularly useful for breaking down a string into parts.

    const gameName = new String('Cricket-Football-Tennis-Basketball')
    let result = gameName.split('-')
    console.log(result); //Output: [ 'Cricket', 'Football', 'Tennis', 'Basketball' ]
    console.log(typeof result); //Output: Object
    
    result2 = gameName.split('-',3)
    console.log(result2); //Output: [ 'Cricket', 'Football', 'Tennis' ]
    
  11. String.startsWith(): This method returns a boolean value (true or false) based on the check

    let str1 = "Hello, World!";
    let startsWithHello = str1.startsWith("Hello"); 
    console.log(startsWithHello); //Output: true
    let startsWithWorld = str1.startsWith("World!"); 
    console.log(startsWithWorld); //Output: false
    
  12. String.endsWith(): This method returns a boolean value (true or false) based on the check.

    let str1 = "Hello, World!";
    let startsWithHello = str1.endsWith("Hello"); 
    console.log(startsWithHello); //Output: false
    let startsWithWorld = str1.endsWith("World!"); 
    console.log(startsWithWorld); //Output: true
    
  13. String.match(): The match method is used to retrieve the matches when a string matches a regular expression. This method is applied to a string and returns an array containing the matched substrings if the match is not found then null will be returned.

    let str = "The rain in Spain falls mainly in the plain.";
    let matches = str.match(/ain/g);
    // Output: ["ain", "ain", "ain", "ain"]
    console.log(matches);
    let matches2 = str.match(/drain/g);
    console.log(matches2);// Output: null
    
  14. String.includes(): This method returns a boolean value (true or false) based on the check. If the check is present in the given string then true will be returned and if the check is not present in given string then false will be returned

    let str1 = "Hello, World!";
    console.log(str1.includes("H")) //Output: true
    console.log(str1.includes("World")) //Output: true
    console.log(str1.includes("Universe")) //Output: false
    
  15. String.test(): This method returns a boolean value (true or false) based on the pattern check.

    let str = "The rain in Spain falls mainly in the plain.";
    let pattern = /ain/;
    let hasPattern = pattern.test(str);
    console.log(hasPattern); //Output: true
    
    let pattern2 = /drain/;
    let hasPattern2 = pattern2.test(str);
    console.log(hasPattern2); //Output: false