JavaScript String Methods Unleashed: Practical Uses and Real-world Examples💥

JavaScript String Methods Unleashed: Practical Uses and Real-world Examples💥

·

9 min read

⛳Introduction

To Kaise Hai Aap Log So How Are You Guys GIF - To Kaise Hai ...

Hello fellow coders 👩‍💻👨‍💻! After a long hiatus, I finally have some time to spare, and I've decided to write a blog focusing on JavaScript string methods. Whether you're a fresher entering the world of coding or an experienced developer working on projects, it's essential to have a solid understanding of these methods. In this blog, we'll explore and dissect JavaScript string methods in simple terms with plenty of examples. By the end of it, you'll have a clear understanding, ensuring you won't forget these methods anytime soon. So, are you ready? Let's dive in and demystify JavaScript string methods together!

Chaliye shuru karte hain bina kisi Binod ke meme - HindiBate.CoM

🎯What is string?

In JavaScript, a string is a sequence of characters enclosed within single (' ') or double (" ") quotation marks.

Strings can contain letters, numbers, symbols, and special characters.

They are used to represent text data and are one of the primitive data types in JavaScript.

Here's a simple definition:

"A string in JavaScript is a sequence of characters enclosed within single or double quotation marks, used to represent text data."

1.JavaScript String Length

The length property returns the length of a string:

let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = text.length;
console.log(length)

2.Extracting String Characters

There are 4 methods for extracting string characters:

  • The at(position) Method

  • The charAt(position) Method

  • The charCodeAt(position) Method

  • Using property access [] like in arrays

JavaScript String charAt()

  • The charAt() method returns the character at a specified index (position) in a string:

  •   const str = "Hello"; 
      const char = str.charAt(0); // Output: "H" 
      console.log(char)
    

    JavaScript String charCodeAt()

    The charCodeAt() method returns the code of the character at a specified index

    in a string:

    The method returns a UTF-16 code (an integer between 0 and 65535).

  •   let text = "HELLO CODERS";
      let char = text.charCodeAt(0);//Output:72
      console.log(char)
    

    JavaScript String at()

    ES2022 introduced the string method at():

  • The at() method returns the character at a specified index (position) in a string.

    The at() method is supported in all modern browsers since March 2022:

  •   //Get the third letter of name:
      const name = "W3Schools";
      let letter = name.at(2);//Output:"S"
      console.log(letter)
    
      //both are same
      const nameone = "W3Schools";
      let letterone = nameone[2];////Output:"S"
      console.log(letterone)
    

    Note👉

    📍The at() method is a new addition to JavaScript.

    📍It allows the use of negative indexes while charAt() do not.

Property Access [ ]

  •   let text = "HELLO WORLD";
      let char = text[0];//Output:"H"
      console.log(char)
    
      let textone = "HELLO WORLD";
      let charone = textone[12];//Output:undefined
      console.log(charone)
    

    Note

    Property access might be a little unpredictable:

    • It makes strings look like arrays (but they are not)

    • If no character is found, [ ] returns undefined, while charAt() returns an empty string.

    • It is read only. str[0] = "A" gives no error (but does not work!)

    •   let text = "HELLO WORLD";
        text[0] = "A";  // Attempting to modify the first character to "A"
        console.log(text);  // Output: "HELLO WORLD"
        //JavaScript, strings are immutable, which means you cannot change individual 
        //characters within a string directly.
      

Garam Masala Akshay Kumar GIF - Garam Masala Akshay Kumar Samajh Me Nahi Aata Meri Kismat Me Ye Khatam Kab Hoga GIFs

  • "I know some of you may be wondering how many methods there are. But don't worry, I'll cover them all soon. If you start feeling bored, take a break and watch a fun GIF to lift your spirits. Then, come back and continue reading the blog and practicing the methods. Don't stop until you've finished!"

    Carryminati Ajey Nagar GIF - Carryminati Ajey Nagar GIFs

    concat(): Concatenates two or more strings together and returns a new string.

      const str1 = "Hello";
      const str2 = "World";
      const result = str1.concat(" ", str2); // Output: "Hello World"
      console.log(result)
    

    indexOf(): Returns the index of the first occurrence of a specified substring within the string, or -1 if not found.

      const str = "Hello World";
      const index = str.indexOf("World"); // Output: 6
      console.log(index)
    

slice(): Extracts a section of a string and returns it as a new string.

The method takes 2 parameters: start position, and end position (end not included).

  •   const str = "Hello World";
      const sliced = str.slice(6); // Output: "World"
      console.log(sliced)
    
      //Slice out a portion of a string from position 7 to position 13:
      let text = "Apple, Banana, Kiwi";
      let part = text.slice(7, 13);// Output: "Banana"
      console.log(part)
      //If a parameter is negative, the position is 
      //counted from the end of the string:
      let text = "Apple, Banana, Kiwi";
      let part = text.slice(-12);// Output:"Banana, Kiwi"
      console.log(part)
    
      //This example slices out a portion of a string from 
      // position -12 to position -6:
      let text = "Apple, Banana, Kiwi";
      let part = text.slice(-12, -6);// Output:"Banana"
      console.log(part)
    

substring(): Similar to slice(), but does not support negative indexes.

  •   const str = "Hello World";
      const sub = str.substring(6); // Output: "World"
      console.log(sub)
    

    Converting to Upper and Lower Case

    A string is converted to upper case with toUpperCase():

    A string is converted to lower case with toLowerCase():

    •     const str = "hello";
          const upperCaseStr = str.toUpperCase(); // Output: "HELLO"
          console.log(upperCaseStr)
      
          const str = "HELLO";
          const lowerCaseStr = str.toLowerCase(); // Output: "hello"
          console.log(lowerCaseStr)
      

      replace(): Replaces a specified value or pattern with another string.

      •   const str = "Hello World";
          const replaced = str.replace("World", "Universe"); // Output: "Hello Universe"
          console.log(replaced)
        

        split(): Splits a string into an array of substrings based on a specified separator.

      •   const str = "apple,banana,grape";
          const arr = str.split(","); // Output: ["apple", "banana", "grape"]
          console.log(arr)
        

        trim(): Removes whitespace from both ends of a string.

      •   const str = "   Hello World   ";
          const trimmed = str.trim(); // Output: "Hello World"
          console.log(trimmed)
        

        trimEnd(): Removes whitespace from the end of a string.

          javascriptCopy codeconst str = "   Hello World   ";
          const trimmedStr = str.trimEnd(); // Output: "   Hello World"
          console.log(trimmedStr)
        

        trimStart(): Removes whitespace from the beginning of a string.

          javascriptCopy codeconst str = "   Hello World   ";
          const trimmedStr = str.trimStart(); // Output: "Hello World   "
          console.log(trimmedStr)
        

        startsWith(): Checks if a string starts with a specified substring.

          const str = "Hello World";
          const startsWithHello = str.startsWith("Hello"); // Output: true
          console.log(startsWithHello)
        
      • endsWith(): Checks if a string ends with a specified substring.

          const str = "Hello World";
          const endsWithWorld = str.endsWith("World"); // Output: true
          console.log(endsWithWorld)
        

        Oye Bas Kar Bhai Pagal Kardiya GIF - Oye Bas Kar Bhai Pagal Kardiya Piccha Chhod De Mera GIFs

        padEnd(): Pads the current string with a given string (repeated, if needed) so that the resulting string reaches a given length. The padding is applied from the end of the current string.

      •   const str = "Hello";
          const paddedStr = str.padEnd(10, " World"); // Output: "Hello World"
          console.log(paddedStr)
        

        padStart(): Pads the current string with a given string (repeated, if needed) so that the resulting string reaches a given length. The padding is applied from the start of the current string.

          const str = "World";
          const paddedStr = str.padStart(10, "Hello "); // Output: "Hello World"
          console.log(paddedStr)
        

        The padEnd() and padStart() methods are particularly useful in scenarios where you need to format strings to achieve consistent alignment or padding, which is quite common in real-world projects, especially when dealing with tabular data, displaying messages, or generating fixed-width text output.

        Here are a few real-world scenarios where padEnd() and padStart() might be used:

      • Displaying Tabular Data: When you're displaying tabular data, you might need to ensure that columns are aligned properly. For instance, when printing a table, you might pad shorter entries in a column with spaces to make sure all entries align properly.

      •   const data = [
              { name: "Alice", age: 25 },
              { name: "Bob", age: 30 },
              { name: "Charlie", age: 35 }
          ];
        
          data.forEach(entry => {
              console.log(`${entry.name.padEnd(10)}${entry.age.toString().padStart(5)}`);
          });
        

      • Formatting Strings: When generating strings for display or logging, you might want to ensure a consistent length for readability or aesthetic reasons.

        1.  const title = "Welcome to our Website";
           const formattedTitle = title.padStart(title.length + 5, "-").padEnd(title.length + 10, "-");
           console.log(formattedTitle);
          

          This code adds padding to both sides of the title to center it and make it stand out.

          Message Formatting: In messaging applications or when generating log messages, you might want to ensure consistent formatting for readability.

           const user = "Alice";
           const message = "Hello, how are you?";
           const formattedMessage = `${user}:`.padEnd(15) + message;
           console.log(formattedMessage);
          

          This code formats a message to include the username followed by a colon, ensuring consistent spacing.

Overall, padEnd() and padStart() are handy methods for formatting strings and ensuring consistent alignment, which can improve the readability and presentation of data in real-world projects.

  • Dear Zindagi.Gif GIF - Dear Zindagi Shah Rukh Khan Alia Bhatt GIFs

replaceAll(): Replaces all occurrences of a specified substring or regular expression with another string.

        const str = "Hello World Hello";
        const replacedStr = str.replaceAll("Hello", "Hi"); // Output: "Hi World Hi"
        console.log(replacedStr)
  • search(): Searches a string for a specified value or regular expression. Returns the index of the first match found, or -1 if not found.

      const str = "Hello World";
      const index = str.search("World"); // Output: 6
      console.log(index)
    
  • repeat(): Returns a new string consisting of the original string repeated a specified number of times.

      const str = "Hello";
      const repeatedStr = str.repeat(3); // Output: "HelloHelloHello"
      console.log(repeatedStr)
    
  • substr(): Returns a portion of the string, starting at the specified index and extending for a given number of characters.

      const str = "Hello World";
      const substring = str.substr(6, 5); // Output: "World"
      console.log(substring)
    
  • valueOf(): Returns the primitive value of a string object.

      const str = new String("Hello");
      const primitiveValue = str.valueOf(); // Output: "Hello"
      console.log(primitiveValue)
    

Rahul Gandhi GIF - Rahul Gandhi Akashrajput GIFs

🎯 Wrap Up!!

Thank You Appreciate It GIF - Thank You Appreciate It Flattered GIFs

"Thank you for taking the time to read my blog! I hope you found it helpful. If you have any questions or concerns, please feel free to reach out to me on LinkedIn or Twitter. If you found this blog useful, don't forget to like and share it with your friends. Your valuable comments are greatly appreciated. Thank you all for staying connected with me and for your continued support. I'll strive to cover more interesting topics in the coming weeks. Until next time, Happy coding!"

Did you find this article valuable?

Support <YouCanCode/> by becoming a sponsor. Any amount is appreciated!