Javascript Strings

Strings are collection of characters stored within quotes. Strings can have lower case, upper case, special characters, or numbers within quotes.

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

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

Backslash, i.e. \ is used inside strings to ignore character. For exp var x="abc\"pqr";

JavaScript Strings Example


 var x="Tech Altum";    // string; 
 var y='Tech Altum';    // string; 
 var z=`Tech Altum`;    // template literal in ES6 
 var i="9";             // string
 var j='9';             // string

Template Literals

ES6 introduced Template Literals or Template Strings in javascript by using back-tick or grave characters. To insert a placeholder variable in template iteral, use ${expression} inside.


var x=3;
var 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"

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 shows the number of characters in string.


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

String length property is immutable, means if length of string is 8 and we assign string.length to 10, it will still return 8. See example


    var 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.


    var 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.

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.


    var 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.


    var x="tech altum"; 
    
    x.indexOf("t")             // return 0;
    x.lastIndexOf("t")         // return 7;
    x.lastIndexOf("e")         // return 2;

concat

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


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

+ operator can also concat two strings in javascript.


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

charAt

charAt method return character at given index in argument.


    var 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.


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

toUpperCase

toUpperCase method convert all lowercase characters to uppercase.


    var 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.


    var x="Tech Altum"; 
    
    x.toUpperCase();    // return "techaltum"

substr

substr method return substrings from index (first argument ) to given length (second argument). First argument is always index and second is length. If second argument is missing, it will return substrings from index (argument).


    var 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"

For IE8 and below, use substring


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


    var 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.


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

replace

replace method is used to replace a single or multiple characters with a new characters. The first argument is replaced character, and second is replacing one.


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

split

split method splits a string to array


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


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.