Strings

Strings are collection of characters stored inside quotes ( double / single) or back tick (in ES6). Strings represents text and can have lower case, upper case, special characters or numbers within quotes.

Strings can store data, like name, email id, age etc. Default datatype for input, select, textarea value is always a string.

In JavaScript, Strings are declared inside double quotes "" or single quotes ''. Strings started with double quotes should be closed by double quotes, and strings started with single quotes should be closed by single quotes. Both var x="hello" and var x='hello' are the same in JavaScript.

A backslash, i.e., \, is used inside strings to escape characters. For example, var x="abc\"pqr";

We can also declare strings using let or const in ES6.

Declare Strings in JavaScript


 const x="Tech Altum";    // string;
 const y='Tech Altum';    // string;
 const z=`Tech Altum`;    // ES6 template literal

 const str=String("abc"); // String class/function

JavaScript String can store at max 2^53 - 1 characters as per ECMAScript 2016 (ES7).



Template Literals

ES6 introduced Template Literals or Template Strings in javascript by using back-tick or grave characters.


let str=`js string`;                

String interpolation via template literal

To string interpolation or to insert a placeholder variable in template literal, use ${expression} inside.


const x=3;
const y=5;
console.log(`sum of ${x} and ${y} is ${x+y}`);  //ES6

console.log("sum of " + x + " and " + y + " is " + (x+y));  //ES5

// returns "sum of 3 and 5 is 8"

Multi line string

Template literals can also add multi-line strings. Till ES5, we use + operator to do the same. See example of Multi line string .


    let template=`<!div>
    this is div   
    </div>`;

Properties of String

JavaScript Strings can have properties, like length. Properties are information about that string. Properties are checked using Dot notation (.) or brackets [ ] with property name in quotes. See example

String.length

String.length property returns the number of characters in the string. Note that for Unicode characters outside the Basic Multilingual Plane (like some emojis), the length might not match the visual character count due to UTF-16 encoding.

8


    let x="hello js";
    x.length;            // 8       

4


    let x="😁😂";
    x.length;            // 4       

String length is an immutable or read-only property. This means that if the length of a string is 8 and we try to assign a new value to string.length, it will remain unchanged. See example:


    const x="hello js";
    x.length;         // 8   
    
    x.length=10;
    x.length;        // 8    
           
    x.length=2;
    x.length;        // 8        

Empty String

An empty string is the string with length equals to zero.


    let x="";
    x.length;    // 0                            
                   


String Methods

JavaScript Methods are build in functions used to perform an action to strings. All methods are called by method name and then parenthesis. Parameters are passed inside parenthesis if required.

For exp, x.age is property, but x.getAge() is a method.

at

at methods returns character at particular index.


const x="tech altum"; 
            
x.at(0)     // return "t";
x.at(1)     // return "e";
x.at(-1)    // return "m";

indexOf

indexOf methods returns index of first matched substring. The return value of indexOf methods is always a number.

If substring is not found, it will return -1.


    const x="tech altum"; 
    
    x.indexOf("t")         // return 0;
    x.indexOf("e")         // return 1;
    x.indexOf("b")         // return -1;

        

lastIndexOf

lastIndexOf methods returns index of last matched substring. The return value of lastIndexOf method will also be number.

If substring is not found, it will return -1.


    let x="tech altum"; 
    
    x.indexOf("t")             // return 0;
    x.lastIndexOf("t")         // return 7;
    x.lastIndexOf("e")         // return 1;
    x.lastIndexOf("z")         // return -1;

concat

concat method is used to concatenate or merge two strings into one. The second string should be passed as argument.


    let x="tech"; 
    let y="altum"; 
    
    x.concat(y);    // return techaltum

+ operator can also concat two strings in javascript.


    let x="tech"; 
    let y="altum"; 
    
    x+y;    // return techaltum

charAt

charAt method return character at given index in argument.


    let x="techaltum"; 
    
    x.charAt(0);    // return t
    x.charAt(1);    // return e
    x.charAt(x.length-1);    // return m
    x.charAt(x.length);      // return ""

charCodeAt

charCodeAt method return ASCII code of character at given index in argument.


    let x="techaltum"; 
    
    x.charCodeAt(0);    // return 116
    x.charCodeAt(1);    // return 101

toUpperCase

toUpperCase method convert all lowercase characters to uppercase.


    let x="techaltum"; 
    
    x.toUpperCase();    // return "TECHALTUM"

toUpperCase method only return string in uppercase, but value of x will remain same, .ie. lowercase


toLowerCase

toLowerCase method convert all uppercase characters to lowercase.


    let x="Tech Altum"; 
    
    x.toLowerCase();    // return "techaltum"

substr

substr method returns a substring from the string starting at the index specified by the first argument, for the number of characters specified by the second argument. The first argument is the starting index, and the second is the number of characters to include. If the second argument is omitted, it returns all characters from the starting index to the end of the string. See examples:


    let x="techaltum"; 
    
    x.substr(2);        // return "chaltum"
    x.substr(4);        // return "altum"
    
    x.substr(0,4);        // return "tech"
    x.substr(2,2);        // return "ch"
    x.substr(4,5);        // return "altum"

substring

substring method returns a substring from the string between the start and end indices specified. The first argument is the start index (inclusive), and the second is the end index (exclusive). If the second argument is omitted, it returns from the start index to the end of the string.


    let x="techaltum"; 
    
    x.substring(0,4);        // return "tech"
    x.substring(2,6);        // return "chal"
    x.substring(4);          // return "altum"

slice

slice method is similar to substring but can accept negative indices, which count from the end of the string. The first argument is the start index, and the second is the end index (exclusive).


    let x="techaltum"; 
    
    x.slice(0,4);        // return "tech"
    x.slice(-4);         // return "ltum"
    x.slice(2,-2);       // return "chal"

search method search for a matched pattern between string and regular expression and return index of matched pattern.


    let x="tech altum"; 
    x.search("t");        // return 0
    x.search("T");        // return -1
    
    x.search(/\s/);        
    // return 4, i.e, white space found at 4th index
    
    x.search(/\d/);        
    // return -1, i.e, no digit found

To know more about regular expressions, click here. JavaScript Regular Expressions


trim

trim method trim extra whitespace from beginning and ending of a string and returns a new string without changing existing one.


    let x=" tech altum ";
    x.trim();    // return "tech altum" 
 

trimStart()

trimStart() methods remove whitespace from beginning of a string and returns a new string


    let x=" tech altum ";
    x.trimStart();    // return "tech altum "
    

trimEnd()

trimEnd() methods remove whitespace from ending of a string and returns a new string


    let x=" tech altum ";
    x.trimEnd();    // return " tech altum"
    

replace

replace method replaces the first occurrence of a substring (first argument) with a new substring (second argument) and returns the modified string. The original string remains unchanged.


    let x="tech altum";
    x.replace("t","T")            // return "Tech altum" 
    x.replace("tech","TECH")      // return "TECH altum" 
    x.replace(" ","-")            // return "tech-altum" 
 

Replace all characters from string


    let x="tech altum";
    
    x.replace(/t/,"T");        // return Tech  altum  
    x.replace(/t/g,"T");       // return Tech  alTum  
       

replaceAll

replaceAll method is used to replace all characters or words with a new character/words. The first argument is character to be replaced, and second is replacing one.


    let x="tech altum";

    x.replace("t","T")            // return "Tech altum" 
    x.replaceAll("t","T")        // return "Tech alTum" 
 

split

split method splits a string to array by argument given.


    let x="tech altum";
    x.split("");         // return ["tech altum"]
    x.split(" ");        // return ["tech","altum"]


startsWith

string.startsWith method is used to check if the given strings starts with specific characters or not. This will return true or false.


    let x="tech altum";
    
    console.log(x.startsWith("t"));            // true
    console.log(x.startsWith("T"));             // false
    console.log(x.startsWith("a"));            // false

endsWith

string.endsWith method is used to check if the given strings ends with specific characters or not. This will also return true or false.


    let x="tech altum";
    
    console.log(x.endsWith("m"));            // true
    console.log(x.endsWith("t"));            // false

includes

string.includes method is used to check if the given strings contain specific characters or not. This will also return true or false.


    let x="tech altum";
    
    console.log(x.includes("ch"));            // true
    console.log(x.includes("cm"));            // false

Summary

JavaScript strings are fundamental for handling text data. You can declare them using single quotes, double quotes, or backticks for template literals introduced in ES6. Strings have a length property and numerous methods for manipulation:

  • Accessing characters: at(), charAt(), charCodeAt()
  • Finding substrings: indexOf(), lastIndexOf(), search()
  • Modifying strings: toUpperCase(), toLowerCase(), trim(), trimStart(), trimEnd(), replace(), replaceAll()
  • Extracting parts: substr() (deprecated), substring(), slice(), split()
  • Checking contents: startsWith(), endsWith(), includes()
  • Concatenation: concat() method or + operator
  • Creating from codes: String.fromCharCode()

Mastering these string methods will greatly enhance your JavaScript programming skills. Practice with real-world examples to solidify your understanding.


Get String from ASCII Code

To get string value from ASCII code, use String.fromCharCode method and pass ASCII code as argument. See example


    String.fromCharCode(102);    // return f
    String.fromCharCode(65);    // return A

"+" operator and "concat()" method, both concat strings in javascript.


Video