Javascript Strings

strings are common text type data. It is collection of any character i.e. lower case, upper case, special characters, or numbers.

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 closeed 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";

 var x="Tech Altum";    // string; 
 var y='Tech Altum';    // string; 
 var z="9";             // string
 var a='9';             // string

Properties of string

JavaScript Strings can have properties, like length.

JavaScript String Properties

lengthreturn no of characters var x="tech altum";
x.length // return 10;

Methods of String

JavaScript Methods are build in functions. All methods are called by method name and then parenthesis. Parameters are passed inside parenthesis if needed.

JavaScript String Methods

indexOf("t")return first index of t substring.var x="tech altum";
// return 0;
lastIndexOf("t")return last first index of t substring.var x="tech altum";
// return 7;
concat("x")concat with "." string .var x="tech altum";
// return "tech altum.";
charAt(0)return first character of string.var x="tech altum";
// return "t";
charAt(1)return second character of string.var x="tech altum";
// return "e";
charAt(x.length-1)return last character of variable x.var x="tech altum";
// return "m";
charAt(x.length)return ""var x="tech altum";
// return"";
charCodeAt(0)return character encoding (ASCII value) of substring at 0 index.var x="tech altum";
// return 116;
charCodeAt(1)return character encoding (ASCII value) of substring at 1 index .var x="tech altum";
// return 101;
toUpperCase()convert lower to upper case .var x="tech altum";
// return "TECH ALTUM";
toLowerCase()convert upper to lower case .var x="Tech Altum";
// return "tech altum";
substr(1)return substring after 0 index .var x="tech altum";
// return "ech altum";
substr(2)return substring after 1 index .var x="tech altum";
// return "ch altum";
substr(2,2)return substring between 2 and next 2.var x="tech altum";
// return "ch";
substring(1)return substring after 0 index.var x="tech altum";
// return "ech Altum";
substring(2,4)return substring between 2 and 4 index.var x="tech altum";
// return "ch";
trim()trim method is used to remove extra whitespace before and after string.var x=" tech altum ";
// return "tech altum";
search("tech")return position on substring "tech", i.e 0.var x="tech altum";"tech")
// return 0;
search("Tech")return position on substring "Tech", i.e -1.var x="tech altum";"Tech")
// return -1;

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