String and Methods in JavaScript

Hello, everyone, welcome back, in this module, I am going to discuss string and methods in JavaScript. In the previous module, we learned to break and continue statements in JavaScript. So, let’s start.

String and Methods in JavaScript

In JavaScript, a string is a sequence or group of characters written inside either single or double-quotes. It is used to store data or values in the form of text and perform operations on it.

String and methods in javascript

Example

// string inside double quotes.
let name="My name is Rohit.";
console.log (name);
// string inside single quotes.
const city='I live in India.';
console.log(city);

//Output
//My name is Rohit.
//I live in India.

Unlike other programming languages, in JavaScript, we can also create a string using a backtick character (`), which is just to the left of key 1 in the keyboard.

var message=`Hello, World!`;
console.log(message);

//Output
//Hello, World!

How to create a string?

In JavaScript, we can create a string in 2 ways:

Primitive or string literal

We can create strings using primitive or string literal by enclosing the string value inside single or double-quotes.

Syntax

let variable_name="string value"
var variable_name='string value'

Here, we can create a variable using var, let, and const keywords in JavaScript.

let a="Hello";
console.log(typeof(a));

//Output
//string

String object

When a string is created using a new keyword, it is known as a string object.
Syntax
var variable_name=new String(“string value”);

Example

var str=new String("Hello, World");
console.log(typeof(str));

//Output
//Object

How to access the characters of a string?

We can easily access the characters of a string using its index number. The index number starts from 0 and ends at (length of string-1) in the string.

const a="JavaScript"
console.log(a[2]); // v

How to access the characters of a String

String with an escape character

Suppose you want to print the message, This is a “JavaScript” tutorial.
If you print this message in JavaScript like this as shown below, then you will get a syntax error:

console.log("This is a "JavaScript" tutorial.");

So, to print the above message, we can enclose the string inside a single quote.

console.log('This is a "JavaScript" tutorial.');

Another way to print the above message is to use backslash escape characters \.

console.log("This is a \"JavaScript\" tutorial.");

Similarly, we can print the message, This is a ‘JavaScript’ tutorial, using either backslash escape characters or enclosing the string inside double-quotes.

console.log("This is a 'JavaScript' tutorial.");
console.log('This is a \'JavaScript\' tutorial.');

String methods in JavaScript

  1. charAt()
    It is used to return the character in the string at the given index.
    Syntax
    string.charAt(index)
    Example

    const a="String in JavaScript."
    console.log(a.charAt(5));
    
    //Output
    //g
    
  2. charCodeAt()
    It is used to return the Unicode of the character at the given index in a string.
    Syntax
    string.charCodeAt(index)
    Example

    const s="JavaScript"
    console.log(s.charCodeAt(1));
    
    //Output
    //97
    

    Here, in the above example, the character at index 1 is ‘a’, so its Unicode is 97.
    We can use the length property along with the charCodeAt() method to find the Unicode of the last character in a string.

    Example

    const a="JavaScript";
    let len=a.length;
    console.log(a.charCodeAt(len-1));
    
    //Output
    //116
    
  3. replace()
    This method is used to replace a part of a given string or the whole string with a new string.
    Syntax
    string.replace(original_string,new_string)
    original_string is a string to be replaced.
    new_string is a string used to replace the original string.
    Example

    const a="JavaScript";
    console.log(a.replace("Java","Type"));
    console.log(a.replace("JavaScript","CoffeeScript"));
    
    //Output
    //TypeScript
    //CoffeeScript
    

    We can also use regular expressions in place of the original_string to be replaced with a new string.

    Example

    const a="JavaScript is a Programming Language.";
    console.log(a.replace("a","A"));
    console.log(a.replace(/a/g,"A"));
    
    //Output
    //JAvaScript is a Programming Language.
    //JAvAScript is A ProgrAmming LAnguAge.
    

    Here, in the above example, when we are not using a regular expression, only the first occurrence of ‘a’ is replaced with ‘A’ but with the use of a regular expression, all the character ‘a’ gets replaced with ‘A’. In the given regular expression /a/g, g means that the character ‘a’ is searched globally in a given string and gets replaced with ‘A’.

  4. concat()
    It is used to join or concatenate two or more strings.
    Syntax
    string.concat(string1,string2)
    Example

    const s1='String';
    const s2='in';
    const s3='JavaScript'
    console.log(s3.concat(s1));
    console.log(s1.concat(s2,s3));
    console.log(s1.concat(' ',s2,' ',s3));
    
    //Output
    //JavaScriptString
    //StringinJavaScript
    //String in JavaScript
    
  5. fromCharCode()
    This method is used to return the ASCII character of a given Unicode. It uses a String object instead of a given string to invoke itself.
    Syntax
    String.fromCharCode(Unicode)
    Example

    console.log(String.fromCharCode(97));
    console.log(String.fromCharCode(78));
    
    //Output
    //a
    //N
    
  6. trim()
    It is used to remove white spaces from both ends of a given string.
    Syntax
    string.trim()
    Example

    var str = " Trim method in JS. ";
    console.log(str.trim());
    
    //Output
    //Trim method in JS.
    
  7. startsWith()
    It is a method used to return true if the given string starts with the specified character or string, otherwise, it returns false.
    Syntax
    string.startsWith(string)
    Example

    const str='Programming language';
    console.log(str.startsWith('P'));
    console.log(str.startsWith('program'));
    
    //Output
    //true
    //false
    

    startsWith() is a case sensitive method, which means that uppercase and lowercase letters are treated differently.

    Example

    const str='Programming language';
    console.log(str.startsWith('Program'));
    console.log(str.startsWith('program'));
    
    //Output
    //true
    //false
    

    We can also provide a start position up to which the given character or string to be searched within a string.

    Syntax
    string.endsWith(string,startposition)
    startposition is an index number.

    Example

    const str='JavaScript';
    console.log(str.startsWith('Java',0));
    console.log(str.startsWith('Java',3));
    console.log(str.startsWith('Script',4));
    
    //Output
    //true
    //false
    //true
    
  8. endsWith()
    This method is used to return true if the given string starts with the specified character or string, otherwise, it returns false.
    Syntax
    string.endsWith(string)
    Example

    const str='Programming language';
    console.log(str.endsWith('age'));
    console.log(str.endsWith('g'));
    
    //Output
    //true
    //false
    

    We can also provide an end position up to which the given character or string to be searched within a string.

    Syntax
    string.endsWith(string,endposition)
    endposition is an index number.

    As I have mentioned earlier, the index of a string starts from 0, so the string is searched from 0 to endposition -1.

    Example

    const str='JavaScript';
    console.log(str.endsWith('Java',4));
    console.log(str.endsWith('Java',3));
    console.log(str.endsWith('Script',10));
    
    //Output
    //true
    //false
    //true
    

    endsWith() is a case sensitive method, which means that uppercase and lowercase letters are treated differently.

    Example

    const str='Programming language';
    console.log(str.endsWith('age'));
    console.log(str.endsWith('Age'));
    
    //Output
    //true
    //false
    
  9. toString()
    It is used to convert a numeric or boolean value to a string.
    Syntax
    string.toString(number)
    string.toString(boolean)
    Example

    let num=5;
    console.log(typeof num);
    num=num.toString();
    console.log(typeof num);
    
    let bool=true;
    console.log(typeof bool);
    bool=bool.toString();
    console.log(typeof bool);
    
    //Output
    //number
    //string
    //boolean
    //string
    
  10. toUpperCase()
    It is used to convert the given string into uppercase.
    Syntax
    string.toUpperCase()
    Example

    let name='Rahul Sharma';
    console.log(name.toUpperCase());
    
    //Output
    //RAHUL SHARMA
    
  11. toLowerCase()
    It is used to convert the given string into lowercase.
    Syntax
    string.toLowerCase()
    Example

    let name='RAHUL SHARMA';
    console.log(name.toLowerCase());
    
    //Output
    //rahul sharma
    
  12. repeat()
    This method is used to print the given string ‘n’ number of times.
    Syntax
    string.repeat(n)
    where n is the number of times a string or character is printed.
    Example

    let s='Hii';
    console.log(s.repeat(5));
    
    //Output
    //HiiHiiHiiHiiHii
    
  13. search()
    It is used to find a string within a given string and return the starting index number of the string to be searched for if found otherwise, it returns -1.
    Syntax
    string.search(search_string)
    search_string is the string to be searched in a given string.
    Example

    var str='This is a JavaScript tutorial.';
    console.log(str.search('JavaScript'));
    
    //Output
    //10
    
    var a='This is a JavaScript tutorial.';
    console.log(a.search('The'));
    
    //Output
    //-1
    

    search() is a case-sensitive method.

    Example

    var str='This is a JavaScript tutorial.';
    console.log(str.search('JavaScript'));
    console.log(str.search('javascript'));
    
    //Output
    //10
    //-1
    
  14. includes()
    If the given string or character is found within a string, it returns true otherwise it returns false. It is a case-sensitive method.
    Syntax
    string.includes(search_string)
    Example

    var str='This is a JavaScript tutorial.';
    console.log(str.includes('Java'));
    console.log(str.includes('the'));
    
    //Output
    //true
    //false
    

There are many more string methods in JavaScript. The list of other string methods is listed below:

  • indexof()
  • lastIndexOf()
  • split()
  • slice()
  • substr()
  • substring()

I hope this module has helped you a lot to know about strings and their methods in JavaScript. Try all the methods by yourself to gain a better understanding of the string. For more modules, stay connected with us. Keep coding!