JavaScript Strings

In JavaScript, a string is a primitive data type that is used for textual data. JavaScript string must be enclosed in single quotes, double quotes, or backticks. The followings are string literals in JavaScript.

Example: String literals
"Hello World"

'Hello World'

`Hello World`

The string literal can be assigned to a variable using the equal to = operator.

Example: String Variables
let str1 = "This is a double quoted string.";

let str2 = 'This is a single quoted string.';

let str3 = `This is a template string.`;

The template string (using backticks) is used when you want to include the value of a variable or expressions into a string. Use ${variable or expression} inside backticks as shown below.

Example: Template String
let amount = 1000, rate = 0.05, duration = 3; 
let result = `Total Amount Payble: ${amount*(1 + rate*duration)}`;

The template string can be spanned in multiple lines which is not allowed with a single or double quoted string, as shown below.

Example: Template String
let str1 = `This 
            is
            multi-line 
            string`;

/*let str2 = "This 
            will
            give
            error"; */

JavaScript string can be treated like a character array. You can access a character in a string using square brackets [index] or using the str.at(pos) method.

Example: String as array
let str = 'Hello World';

let ch1 = str[0] // H
let ch2 = str[1] // e
let ch3 = str.at(2) // l
let ch4 = str.at(3) // l

str[4] = "P"; //error

JavaScript strings can be accessed using a for loop, as shown below.

Example: Use for Loops
let str = 'Hello World';

for(let i =0; i< str.length; i++)
  console.log(str[i]);

for(let ch of str)
    console.log(ch);

Quotes Inside String

You can include single quotes in double-quoted string or include double quotes in a single quoted string. However, you cannot include a single quotes in single quoted string and double quotes in double-quoted string.

Example: Quotes in string
let str1 = "This is 'simple' string";

let str2 = 'This is "simple" string';

let str3 = `This is 'simple' and "easy" string`;

If you want to include the same quotes in a string value as surrounding quotes then use a backward slash (\) before the quotation mark inside the string value.

Example: Quotes in string
let str1 = "This is \"simple\" string";

let str2 = 'This is \'simple\' string';

String Concatenation

JavaScript string can be concatenated using the + operator or string.concat() method.

Example: String concatenation
let str1 = 'Hello ';
let str2 = "World ";

let str3 = str1 + str2; //Hello World
let str4 = str1.concat(str2);//Hello World

String Objects

JavaScript allows you to create a string object using the new keyword, as shown below.

Example: String object
let str1 = new String(); //create string object
str1 = 'Hello World'; //assign value

// or 

let str2 = new String('Hello World'); //create and assign value 

String objects and string literals are different. The typeof() method will return the type of a variable. The following distinguished string and string objects.

Example: String object
let str1 = new String('Hello World');
let str2 = "Hello World";

typeof(str1); //"object"
typeof(str2); //"string"

Strings Comparison

Two strings can be compared using <, >, ==, === operator, and string.localeCompare(string) method.

The mathematical operators < and > compare two strings and return a boolean (true or false) based on the order of the characters in the string.

The == operator compares the content of strings and === compares the reference equality of strings. The localeCompare() method compares two strings in the current locale. It returns 0 if strings are equal, else returns 1.

Example: String Comparison
console.log("a" < "b"); //true
console.log("b" < "a"); //false
console.log("Apple" == "Apple"); //true
console.log("Apple" == "apple"); //false
console.log("Apple" === "Apple"); //true
console.log("Apple" === "apple"); //false
console.log("Apple".localeCompare("Apple")); //0
console.log("Apple".localeCompare("apple")); //1

Note that the === operator compares the reference of strings objects and not the values.

Example: String Object Comparison
let str1 = "Hello";
let str2 = 'Hello';
let str3 = new String('Hello');

console.log(str1 == str2); //true
console.log(str1 === str2);//true
console.log(str1 == str3); //true
console.log(str1 === str3);//false

JavaScript String Methods & Properties

JavaScript string (primitive or String object) includes default properties and methods which you can use for different purposes.

String Properties

Property Description
length Returns the length of the string.

String Methods

Method Description
charAt(position) Returns the character at the specified position (in Number).
charCodeAt(position) Returns a number indicating the Unicode value of the character at the given position (in Number).
concat([string,,]) Joins specified string literal values (specify multiple strings separated by comma) and returns a new string.
indexOf(SearchString, Position) Returns the index of first occurrence of specified String starting from specified number index. Returns -1 if not found.
lastIndexOf(SearchString, Position) Returns the last occurrence index of specified SearchString, starting from specified position. Returns -1 if not found.
localeCompare(string,position) Compares two strings in the current locale.
match(RegExp) Search a string for a match using specified regular expression. Returns a matching array.
replace(searchValue, replaceValue) Search specified string value and replace with specified replace Value string and return new string. Regular expression can also be used as searchValue.
search(RegExp) Search for a match based on specified regular expression.
slice(startNumber, endNumber) Extracts a section of a string based on specified starting and ending index and returns a new string.
split(separatorString, limitNumber) Splits a String into an array of strings by separating the string into substrings based on specified separator. Regular expression can also be used as separator.
substr(start, length) Returns the characters in a string from specified starting position through the specified number of characters (length).
substring(start, end) Returns the characters in a string between start and end indexes.
toLocaleLowerCase() Converts a string to lower case according to current locale.
toLocaleUpperCase() Converts a sting to upper case according to current locale.
toLowerCase() Returns lower case string value.
toString() Returns the value of String object.
toUpperCase() Returns upper case string value.
valueOf() Returns the primitive value of the specified string object.

String Methods for Html

The following string methods convert the string as a HTML wrapper element.

Method Description
anchor() Creates an HTML anchor <a>element around string value.
big() Wraps string in <big> element.
blink() Wraps a string in <blink> tag.
bold() Wraps string in <b> tag to make it bold in HTML.
fixed() Wraps a string in <tt> tag.
fontcolor() Wraps a string in a <font color="color"> tag.
fontsize() Wraps a string in a <font size="size"> tag.
italics() Wraps a string in <i> tag.
link() Wraps a string in <a>tag where href attribute value is set to specified string.
small() Wraps a string in a <small>tag.
strike() Wraps a string in a <strike> tag.
sub() Wraps a string in a <sub>tag
sup() Wraps a string in a <sup>tag