Methods of String / Javascript

Methods of String / Javascript

·

2 min read

The String is used to represent and manipulate a sequence of characters.

Like these :

const world = "This is a string.";

There are several methods ( or Prototypes) available for manipulating and accessing strings in all over the code file. The list of methods are as follows:

Some of the Highly Used Methods are :

  1. charAt() : It is used to access a single character of a single through its index number. We can acess it by adding .charAt(index) followed by string name like:

     const hello = "This a example of charAt method";
     console.log(hello.charAt(10));  
     // Output of this code is m
    
  2. trim() : It is used for removing unnecessary whitespace from the both ends of a string. We can also remove whitespace of string of specific end by using trimStart() (for whitespace of starting) or trimEnd() (for whitespace of ending).

     const yes = "   Yoo-hoo!   ";
     const no = "text";
     console.log(yes.trim());
     // Output of this code is "Yoo-hoo!" without any space.
     console.log(yes.trimStart(),no);
     /*
     Output of this code is "Yoo-hoo!   text"
     space removed from starting only
     */
     console.log(yes.trimEnd());
     // Output of this code is "   Yoo-hoo!"
    
  3. toLowerCase() : It is used to convert a whole string to Lower Case only. Like :

     const string = "HELLO WORLD"
     console.log(string.toLowerCase());
     // Output of this code is "hello world"
    
  4. toUpperCase : It is used to convert a whole string to Upper Case only. Like :

     const string = "hello world"
     console.log(string.toUpperCase());
     // Output of this code is "HELLO WORLD"
    
  5. slice() : It is used to get a new string from an existing string by using the index number of the existing string for starting and ending of a new string. Using the ending index number is optional, if you don't use this then it will give the output string till the ending. Like this:

     const OneString = "Hi! this is a string."
     // with ending index
     console.log(OneString.slice(2,13));
     // Output of this is "! this is a"
     // without ending index
     console.log(OneString.slice(4));
     // Output of this is "this is a string."
    
  6. concat() : It is used to add any new string in existing string without declaring the string. Like this:

     const hello = "Hi!"
     console.log(hello.concat(" ","Everyone."));
     // Output of this is "Hi! Everyone."
    

Did you find this article valuable?

Support Abhinav by becoming a sponsor. Any amount is appreciated!