JavaScript Strings: Create Strings, Concate, Compare

Here you will learn what string is, how to create, compare and concatenate strings in JavaScript.

String is a primitive data type in JavaScript. A string is textual content. It must be enclosed in single or double quotation marks.

Example: String literal
"Hello World"

'Hello World'

String value can be assigned to a variable using equal to (=) operator.

Example: String literal assigned to a variable
var str1 = "Hello World";

var str2 = 'Hello World';

A string can also be treated like zero index based character array.

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

str[0] // H
str[1] // e
str[2] // l
str[3] // l
str[4] // o

str.length //  11

Since, string is character index, it can be accessed using for loop and for-of loop.

Example: Iterate String
var str = 'Hello World';

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

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

Concatenation

A string is immutable in JavaScript, it can be concatenated using plus (+) operator in JavaScript.

Example: String concatenation
var str = 'Hello ' + "World " + 'from ' + 'TutorialsTeacher ';

Include quotation marks inside string

Use quotation marks inside string value that does not match the quotation marks surrounding the string value. For example, use single quotation marks if the whole string is enclosed with double quotation marks and visa-versa.

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

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

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

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

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

String object

Above, we assigned a string literal to a variable. JavaScript allows you to create a String object using the new keyword, as shown below.

Example: String object
var str1 = new String();
str1 = 'Hello World';

// or 

var str2 = new String('Hello World');

In the above example, JavaScript returns String object instead of primitive string type. It is recommended to use primitive string instead of String object.

Caution:

Be careful while working with String object because comparison of string objects using == operator compares String objects and not the values. Consider the following example.

Example: String object comparison
var str1 = new String('Hello World');
var str2 = new String('Hello World');
var str3 = 'Hello World';
var str4 = str1;

str1 == str2; // false - because str1 and str2 are two different objects
str1 == str3; // true
str1 === str4; // true

typeof(str1); // object
typeof(str3); //string
 

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
Points to Remember:
  1. JavaScript string must be enclosed in double or single quotes (" " or ' ').
  2. String can be assigned to a variable using = operator.
  3. Multiple strings can be concatenated using + operator.
  4. A string can be treated as character array.
  5. Use back slash (\) to include quotation marks inside string.
  6. String objects can be created using new keyword. e.g. var str = new String();
  7. String methods are used to perform different task on strings.
Want to check how much you know JavaScript?